joinÓï¾äÖÐonÌõ¼þÓëwhereÌõ¼þµÄÇø±ð
´ó¸Ù£ºonÊÇÔÚÉú³ÉÁ¬½Ó±íµÄÆð×÷Óã¬whereÊÇÉú³ÉÁ¬½Ó±íÖ®ºó¶ÔÁ¬½Ó±íÔÙ½øÐйýÂË
¡¡¡¡µ±Ê¹ÓÃleft joinʱ£¬ÎÞÂÛonµÄÌõ¼þÊÇ·ñÂú×㣬¶¼»á·µ»Ø×ó±íµÄËùÓмǼ£¬¶ÔÓÚÂú×ãµÄÌõ¼þµÄ¼Ç¼£¬Á½¸ö±í¶ÔÓ¦µÄ¼Ç¼»áÁ¬½ÓÆðÀ´£¬¶ÔÓÚ²»Âú×ãÌõ¼þµÄ¼Ç¼£¬ÄÇÓÒ±í×Ö¶ÎÈ«²¿ÊÇnull£»
¡¡¡¡µ±Ê¹ÓÃright joinʱ£¬ÀàËÆ£¬Ö»²»¹ýÊÇÈ«²¿·µ»ØÓÒ±íµÄËùÓмǼ
¡¡¡¡µ±Ê¹ÓÃinner joinʱ£¬¹¦ÄÜÓëwhereÍêÈ«Ïàͬ¡£
°¸Àýʵ¼ù£º
Êý¾Ý¿âÔÚͨ¹ýÁ¬½ÓÁ½ÕÅ»ò¶àÕűíÀ´·µ»Ø¼Ç¼ʱ£¬¶¼»áÉú³ÉÒ»ÕÅÖмäµÄÁÙʱ±í£¬È»ºóÔÙ½«ÕâÕÅÁÙʱ±í·µ»Ø¸øÓû§¡£
ÔÚʹÓÃleft joinʱ£¬onºÍwhereÌõ¼þµÄÇø±ðÈçÏ£º
1¡¢onÌõ¼þÊÇÔÚÉú³ÉÁÙʱ±íʱʹÓõÄÌõ¼þ£¬Ëü²»¹ÜonÖеÄÌõ¼þÊÇ·ñΪÕ棬¶¼»á·µ»Ø×ó±ß±íÖеļǼ¡£
2¡¢whereÌõ¼þÊÇÔÚÁÙʱ±íÉú³ÉºÃºó£¬ÔÙ¶ÔÁÙʱ±í½øÐйýÂ˵ÄÌõ¼þ¡£ÕâʱÒѾûÓÐleftjoinµÄº¬Ò壨±ØÐë·µ»Ø×ó±ß±íµÄ¼Ç¼£©ÁË£¬Ìõ¼þ²»ÎªÕæµÄ¾ÍÈ«²¿¹ýÂ˵ô¡£
¼ÙÉèÓÐÁ½ÕÅ±í£º
±í1£ºtab2
±í1
id | size |
1 | 10 |
2 | 20 |
3 | 30 |
±í2£ºtab2
±í2
size | name |
10 | AAA |
20 | BBB |
30 | CCC |
Á½ÌõSQL£º
¡¡¡¡1¡¢select * from tab1 left join tab2 on (tab1.size = tab2.size) wheretab2.name='AAA'
¡¡¡¡2¡¢select * from tab1 left join tab2 on (tab1.size = tab2.size andtab2.name=¡®AAA¡¯)
µÚÒ»ÌõSQLµÄ¹ý³Ì£º
1¡¢Öмä±íonÌõ¼þ£ºtab1.size = tab2.size
±í3
tab1.id | tab1.size | tab2.size | tab2.name |
1 | 10 | 10 | AAA |
2 | 20 | 20 | BBB |
2 | 20 | 20 | CCC |
3 | 30 | (null) | (null) |
2¡¢ÔÙ¶ÔÖмä±í¹ýÂËwhereÌõ¼þ£ºtab2.name=¡®AAA¡¯
±í4
tab1.id | tab1.size | tab2.size | tab2.name |
1 | 10 | 10 | AAA |
µÚ¶þÌõSQLµÄ¹ý³Ì£º
1¡¢ Öмä±íonÌõ¼þ£ºtab1.size = tab2.size and tab2.name = ¡®AAA¡¯
±í5
tab1.id | tab1.size | tab2.size | tab2.name |
1 | 10 | 10 | AAA |
2 | 20 | (null) | (null) |
3 | 30 | (null) | (null) |
ÒÔÉϽá¹ûµÄ¹Ø¼üÔÒòÊÇleftjoin,right join£¬full joinµÄÌØÊâÐÔ£¬²»¹ÜonÉϵÄÌõ¼þÊÇ·ñΪÕ涼»á·µ»Øleft»òright±íÖеļǼ£¬fullÔò¾ßÓÐleftºÍrightµÄÌØÐԵIJ¢¼¯£¬¶øinner jionûÓÐÕâ¸öÌØÊâÐÔ£¬ÔòÌõ¼þ·ÅÔÚonÖкÍwhereÖУ¬·µ»ØµÄ½á¹û¼¯ÊÇÏàͬµÄ¡£
×¢£ºËùÓеÄÁ¬½ÓÌõ¼þ±ØÐèÒª·ÅÔÚONºóÃ棬²»È»Ç°ÃæµÄËùÓÐLEFTºÍRIGHT¹ØÁª½«×÷Ϊ°ÚÉ裬¶ø²»ÆðÈκÎ×÷Óá£
on¡¢where¡¢havingµÄÇø±ð
¡¡¡¡on¡¢where¡¢havingÕâÈý¸ö¶¼¿ÉÒÔ¼ÓÌõ¼þµÄ×Ó¾äÖУ¬onÊÇ×îÏÈÖ´ÐУ¬where´ÎÖ®£¬having×îºó¡£ÓÐʱºòÈç¹ûÕâÏȺó˳Ðò²»Ó°ÏìÖмä½á¹ûµÄ»°£¬ÄÇ×îÖÕ½á¹ûÊÇÏàͬµÄ¡£µ«ÒòΪonÊÇÏȰѲ»·ûºÏÌõ¼þµÄ¼Ç¼¹ýÂ˺ó²Å½øÐÐͳ¼Æ£¬Ëü¾Í¿ÉÒÔ¼õÉÙÖмäÔËËãÒª´¦ÀíµÄÊý¾Ý£¬°´Àí˵Ӧ¸ÃËÙ¶ÈÊÇ×î¿ìµÄ¡£
¡¡¡¡¸ù¾ÝÉÏÃæµÄ·ÖÎö£¬¿ÉÒÔÖªµÀwhereÒ²Ó¦¸Ã±Èhaving¿ìµãµÄ£¬ÒòΪËü¹ýÂËÊý¾Ýºó²Å½øÐÐsum£¬ËùÒÔhavingÊÇ×îÂýµÄ¡£µ«Ò²²»ÊÇ˵havingûÓã¬ÒòΪÓÐʱÔÚ²½Öè3»¹Ã»³öÀ´¶¼²»ÖªµÀÄĸö¼Ç¼²Å·ûºÏÒªÇóʱ£¬¾ÍÒªÓÃhavingÁË¡£
¡¡¡¡ÔÚÁ½¸ö±íÁª½Óʱ²ÅÓÃonµÄ£¬ËùÒÔÔÚÒ»¸ö±íµÄʱºò£¬¾ÍÊ£ÏÂwhere¸úhaving±È½ÏÁË¡£ÔÚÕâµ¥±í²éѯͳ¼ÆµÄÇé¿öÏ£¬Èç¹ûÒª¹ýÂ˵ÄÌõ¼þûÓÐÉæ¼°µ½Òª¼ÆËã×ֶΣ¬ÄÇËüÃǵĽá¹ûÊÇÒ»ÑùµÄ£¬Ö»ÊÇwhere¿ÉÒÔʹÓÃrushmore¼¼Êõ,¶øhaving¾Í²»ÄÜ£¬ÔÚËÙ¶ÈÉϺóÕßÒªÂý¡£
¡¡¡¡Èç¹ûÒªÉæ¼°µ½¼ÆËãµÄ×ֶΣ¬¾Í±íʾÔÚû¼ÆËã֮ǰ£¬Õâ×ֶεÄÖµÊDz»È·¶¨µÄ£¬¸ù¾Ý֮ǰµÄÖ´ÐÐÁ÷³Ì£¬whereµÄ×÷ÓÃʱ¼äÊÇÔÚ¼ÆËã֮ǰ¾ÍÍê³ÉµÄ£¬¶øhaving¾ÍÊÇÔÚ¼ÆËãºó²ÅÆð×÷Óõģ¬ËùÒÔÔÚÕâÖÖÇé¿öÏÂÁ½ÕߵĽá¹û»á²»Óá£
¡¡¡¡ÔÚ¶à±íÁª½Ó²éѯʱ£¬on±Èwhere¸üÔçÆð×÷Óá£ÏµÍ³Ê×Ïȸù¾Ý¸÷¸ö±íÖ®¼äµÄÁª½ÓÌõ¼þ£¬°Ñ¶à¸ö±íºÏ³ÉÒ»¸öÁÙʱ±íºó£¬ÔÙÓÉwhere½øÐйýÂË£¬È»ºóÔÙ¼ÆË㣬¼ÆËãÍêºóÔÙÓÉhaving½øÐйýÂË¡£Óɴ˿ɼû£¬ÒªÏë¹ýÂËÌõ¼þÆðµ½ÕýÈ·µÄ×÷Óã¬Ê×ÏÈÒªÃ÷°×Õâ¸öÌõ¼þÓ¦¸ÃÔÚʲôʱºòÆð×÷Óã¬È»ºóÔÙi¾ö¶¨·ÅÔÚÄÄÀï¡£