ã¯ããã«
ããã«ã¡ã¯ãååã®80代ç®åå«å ¼ãã£ããããã¡ã³ããµã¼ãã¹èª²ã®åã§ããå¶éæéï¼åã¨ã®ãã¨ã§ãä»æ¥ã®å°åã¯çç¥ã§æ©éã¹ã¿ã¼ãã§ãã
ä»æ¥ã¯JOINã«é¢ãã話ãæã£ã¦ãã¾ãããJOINã«ã¯ä»¥ä¸ã®ï¼ã¤ãããã¾ãã
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- OUTER JOIN
JOINããã¼ãã«ã¨ãã¼ãã«ã®çµåï¼JOINï¼ã¨ããã®ã¯è§£ã£ã¦ããããããã®JOINãä½ãªã®ããç´ããããã§ãããããããã£ãï¼åã§ç解ãããï¼ã¨ããã®ãä»åã®ããã°ã®ç®çã§ããããï¼åçµã¡ã¾ããã®ã§æ©éå§ãã¾ãã
ã¾ããJOINã«é¢ãã¦
JOINã¯ãã¼ãã«ã¨ãã¼ãã«ã®çµåããéã«ä½¿ãã³ãã³ãã§ããæ§æã¯ä»¥ä¸ã®ããã«ãªãã¾ãã
table_a JOIN table_b ON table_a.foreign_key = table_b.primary_key
ä¾ãã°ãæ ç»ã«é¢ãããã¼ã¿ãã¼ã¹ãããã¨ãã¦
SELECT actor.name, movie.name FROM actor JOIN movie ON actor.movie_id = movie.movie_id
ã¨ããã¨ãFROMã«ã¯actorãã¼ãã«ã¨movieãã¼ãã«ãçµåãã¦ä¸¡æ¹ã®ãã¼ãã«ã«å ¥ã£ã¦ãã«ã©ã ãSELECTã§ããããã«ãªãã俳åªåã¨æ ç»åãåæã«åå¾ã§ããããã«ãªãã¾ãã
ããã¦ããã®JOINã®ç¨®é¡ã§ããããINNERãã¨ãOUTERãJOINããã¢ã§ããLEFTãã¨ãRIGHTãJOINããã¢ã§è¦ããã¨è¦ããããã®ã§ãæ¬è¨äºã§ã¯ãããããã»ããã§èª¬æãããã¾ãã
INNER JOINã¨OUTER JOIN
ä¸è¨ã®ããã«actorãã¼ãã«ããããactorãã¼ãã«ã¯å¤é¨ãã¼ã§movie_idãæã£ã¦ãã¾ãããmovie_idã空ã®å ´åããããã¨ãæ³å®ãã¾ãï¼åºæ¼ããæ ç»ããªã俳åªã俳åªãªã®ãè¥å¹²ããããªç¶æ³ã§ããï¼
ãã¡ãã®ãã¼ãã«ãJOINãã¦ã¿ãã¨ã以ä¸ã®ãããªå½¢ã«ãªãã¾ãã
actor_id 3ã®ãç¡åã®äººãã¯ãåºæ¼ããæ ç»ããªãã®ã§ãJOINããã¨ãã«å¤é¨ãã¼ã¨å½ã¦ã¯ã¾ããã¼ãmovieãã¼ãã«ã«ãªãã§ããéã«movieãã¼ãã«ããè¦ã¦ãããåã®åã¯ããã«åºæ¼ãã俳åªãactorãã¼ãã«ã«ãªãç¶æ³ã§ãããã®ãããªç¶æ³ã§ãå½ã¦ã¯ã¾ããã¼ããªãã¬ã³ã¼ããè½ã¨ãã°INNER JOINãè½ã¨ããªããã°OUTER JOINã¨ãªãã¾ãã
LEFT JOINã¨RIGHT JOIN
å·¦çµåãå³çµåã«ãªãLEFT, RIGHT JOINã§ããå·¦ã»å³ã¯çµåã®åºæºã¨ãªããã¼ãã«ãã©ã£ã¡ãªã®ããé¸æããé¸æãããã¼ãã«ã®æ å ±ãæ®ããå½¢ã«åããã¦çµåãè¡ããã¨ã®ãã¨ã«ãªãã¾ãã
ä¾ãã°ã以ä¸ã®ä¾ãã覧ãã ããã
moiveãã¼ãã«ï¼å·¦ï¼ããã¿ãã¨ãç¡åã®äººãã¯çµåã§ããªãã¬ã³ã¼ãã¨ãªãã¾ãããactorãã¼ãã«ï¼å³ï¼ããã¿ãã¨ãåã®åã¯ããã¯çµåã§ããªãã¬ã³ã¼ãã¨ãªãã¾ããã§ãã®ã§ãããããLEFT JOINãRIGHT JOINãããã¨ä»¥ä¸ã®ãããªå½¢ã§JOINãè¡ããã¾ãã
- LEFT JOIN
- RIGHT JOIN
æå¾ã«
ä¼¼ã¦ããããã§ä¼¼ã¦ãªãJOINã®ç¨®é¡ã§ãããINNERã»OUTERã«é¢ãã¦ã¯ã両æ¹ã®ãã¼ãã«ã«ããã¦çµåã§ããªãã¬ã³ã¼ããã©ãå¦çãããããLEFTã»RIGHTã«é¢ãã¦ã¯ãçµåããéã«ã©ã¡ãã®ãã¼ãã«ãåºæºã«ãããããæèããªããSQLãæ¸ãã¦ã¿ãã¨ãç´ããããJOINã®ä½¿ãæ¹ããã¹ã¿ã¼ã§ãããã¨æãã¾ããç§ãSQLãããããæ¸ããããã«ç é½ãç¶ãã¾ãã®ã§ãä¸ç·ã«é å¼µãã¾ãããï¼