鍏充簬 SQL Server 涓 JOIN 鐨勭煡璇嗐侸OIN 鏄暟鎹簱涓渶鍩虹銆佹渶甯哥敤鐨勬搷浣滀箣涓銆傚畠甯姪鎴戜滑浠庡涓〃涓幏鍙栫壒瀹氱殑鏁版嵁锛屽苟灏嗚繖浜涜〃閫氳繃鏌愪簺鍏宠仈鏉′欢杩涜杩炴帴锛屼粠鑰屽疄鐜版暟鎹殑鑱斿悎鏌ヨ鍜屽鐞嗐

鍦ㄦ暟鎹簱鏌ヨ涓紝鎴戜滑缁忓父浼氶亣鍒伴渶瑕佷粠澶氫釜琛ㄤ腑妫绱㈡暟鎹殑鎯呭喌銆傚鏋滄垜浠彧浣跨敤鍗曡〃鏌ヨ锛屾棤娉曡幏鍙栧埌鎴戜滑鎯宠鐨勫畬鏁存暟鎹傝繖鏃讹紝JOIN 鎿嶄綔灏卞彂鎸ヤ簡閲嶈鐨勪綔鐢ㄣ傚畠鑳藉灏嗗涓〃鎸夌収鐗瑰畾鐨勬潯浠惰繘琛岃繛鎺ワ紝杩斿洖婊¤冻鏉′欢鐨勭粨鏋滈泦銆

SQL Server 涓父瑙佺殑 JOIN 绫诲瀷鍖呮嫭 INNER JOIN锛堝唴杩炴帴锛夈丩EFT JOIN锛堝乏杩炴帴锛夈丷IGHT JOIN锛堝彸杩炴帴锛夊拰FULL JOIN锛堝叏杩炴帴锛夈傛瘡绉 JOIN 绫诲瀷閮芥湁鍏剁壒瀹氱殑璇硶鍜屼娇鐢ㄥ満鏅傛帴涓嬫潵锛岃鎴戜滑閫愪竴浜嗚В瀹冧滑銆

1銆両NNER JOIN锛堝唴杩炴帴锛夛細鍐呰繛鎺ヨ繑鍥炰袱涓〃涓弧瓒宠繛鎺ユ潯浠剁殑浜ら泦鏁版嵁銆傚畠閫氳繃姣旇緝杩炴帴鍒楃殑鍊煎皢鐩稿叧琛岀粍鍚堝湪涓璧枫

-- 鍐呰繛鎺ョず渚
SELECT *
FROM 琛ˋ
INNER JOIN 琛˙

ON 琛ˋ.鍒 = 琛˙.鍒;


2銆丩EFT JOIN锛堝乏杩炴帴锛夛細宸﹁繛鎺ヨ繑鍥炲乏琛ㄤ腑鐨勬墍鏈夎鍜屽彸琛ㄤ腑婊¤冻杩炴帴鏉′欢鐨勮銆傚鏋滃彸琛ㄤ腑娌℃湁鍖归厤鐨勮锛屽垯杩斿洖 NULL 鍊笺

-- 宸﹁繛鎺ョず渚
SELECT *
FROM 琛ˋ
LEFT JOIN 琛˙

ON 琛ˋ.鍒 = 琛˙.鍒;


3銆丷IGHT JOIN锛堝彸杩炴帴锛夛細鍙宠繛鎺ヨ繑鍥炲彸琛ㄤ腑鐨勬墍鏈夎鍜屽乏琛ㄤ腑婊¤冻杩炴帴鏉′欢鐨勮銆傚鏋滃乏琛ㄤ腑娌℃湁鍖归厤鐨勮锛屽垯杩斿洖 NULL 鍊笺

-- 鍙宠繛鎺ョず渚
SELECT *
FROM 琛ˋ
RIGHT JOIN 琛˙

ON 琛ˋ.鍒 = 琛˙.鍒;


4銆丗ULL JOIN锛堝叏杩炴帴锛夛細鍏ㄨ繛鎺ヨ繑鍥炲乏琛ㄥ拰鍙宠〃涓殑鎵鏈夎锛屽鏋滄煇涓〃涓病鏈夊尮閰嶇殑琛岋紝鍒欒繑鍥 NULL 鍊笺

-- 鍏ㄨ繛鎺ョず渚
SELECT *
FROM 琛ˋ
FULL JOIN 琛˙

ON 琛ˋ.鍒 = 琛˙.鍒;


閫氳繃鐏垫椿杩愮敤杩欎簺 JOIN 绫诲瀷锛屾垜浠彲浠ユ牴鎹笉鍚岀殑鏌ヨ闇姹傛潵閫夋嫨鏈鍚堥傜殑杩炴帴鏂瑰紡锛屼粠鑰岃幏寰楀噯纭殑鏌ヨ缁撴灉銆

涓轰粈涔堣瀛︿範 JOIN 鍛紵JOIN 鏄 SQL 鏌ヨ涓渶鍩烘湰銆佹渶閲嶈鐨勬搷浣滀箣涓銆傛帉鎻 JOIN 鐨勪娇鐢ㄦ妧宸э紝鑳藉

鎻愰珮鎴戜滑鏌ヨ鍜屽鐞嗘暟鎹殑鏁堢巼鍜岀伒娲绘с侸OIN 鍙互甯姪鎴戜滑澶勭悊澶氫釜琛ㄤ箣闂寸殑鍏宠仈鍏崇郴锛屽疄鐜版暟鎹殑鑱斿悎鏌ヨ銆佹暟鎹瓫閫夊拰鏁版嵁鑱氬悎绛夋搷浣溿傛棤璁烘槸鍦ㄥ紑鍙戜笟鍔″簲鐢ㄧ▼搴忚繕鏄繘琛屾暟鎹垎鏋愶紝JOIN 閮芥槸蹇呬笉鍙皯鐨勬妧鏈箣涓銆

JOIN鐨勫ソ澶勪笉浠呭湪浜庤兘澶熻В鍐冲疄闄呯殑鏁版嵁鏌ヨ闇姹傦紝杩樿兘鎻愬崌鎴戜滑鐨勬暟鎹簱璁捐鍜屼紭鍖栬兘鍔涖傞氳繃鍚堢悊鍦颁娇鐢↗OIN锛屾垜浠彲浠ラ伩鍏嶆暟鎹啑浣欍佹彁楂樻煡璇㈡晥鐜囷紝骞朵紭鍖栨暟鎹簱鐨勬ц兘銆

鍦ㄤ粖澶╃殑瀛︿範涓紝鎴戜滑閫氳繃妗堜緥浠g爜婕旂ず浜嗕笉鍚岀被鍨嬬殑JOIN浣跨敤鏂规硶锛屽府鍔╀綘鏇村ソ鍦扮悊瑙OIN鐨勫簲鐢ㄥ満鏅拰璇硶銆傚悓鏃讹紝鎴戜滑杩樻坊鍔犱簡涓枃娉ㄩ噴锛屼互甯姪浣犳洿娓呮櫚鍦扮悊瑙d唬鐮佺殑鍚箟鍜屽姛鑳姐

JOIN鏄疭QL Server涓潪甯搁噸瑕佺殑鏌ヨ鎿嶄綔锛屽畠涓烘垜浠彁渚涗簡澶勭悊澶氳〃鏁版嵁鍏宠仈鐨勮兘鍔涖傞氳繃鎺屾彙JOIN鐨勪笉鍚岀被鍨嬪拰鐢ㄦ硶锛屾垜浠兘澶熸洿鐏垫椿鍦版煡璇㈠拰澶勭悊鏁版嵁锛屽苟浼樺寲鏁版嵁搴撶殑鎬ц兘銆

甯屾湜鏈枃鑳藉甯姪浣犵悊瑙OIN鐨勬蹇点佽娉曞拰浣跨敤鍦烘櫙锛屽苟涓轰綘鍦⊿QL Server鐨勫涔犲拰瀹炶返涓彁渚涙寚瀵笺傜户缁繁鍏ュ涔燡OIN锛屼綘灏嗚兘澶熸洿鑷鍦版搷浣滄暟鎹簱锛岃В鍐冲鏉傜殑鏁版嵁鏌ヨ闇姹傘


浠ヤ笂灏辨槸SQL澶氳〃鍏宠仈鏌ヨINNER JOIN銆丩EFT JOIN銆丷IGHT JOIN銆丗ULL JOIN鐨勫尯鍒殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=28