MySQL LEFT JOIN / INNER JOIN 中 ON/WHERE 條件 建議規定用法
MySQL LEFT JOIN / INNER JOIN 中 ON/WHERE 條件 建議規定用法
資料來源: https://mp.weixin.qq.com/s/zQkXrlRhJ6Of2COhjYuZXg
結論:在left join語句中,左表過濾必須放where條件中,右表過濾必須放on條件中,這樣結果才能不多不少,剛剛好
EX:
#分別統計每班女性人數(students 是右表所以放在ON) SELECT c.name, count(s.name) AS num FROM classes c LEFT JOIN students s ON s.class_id = c.id and s.gender = 'F' GROUP BY c.name #找出一班的同學總數(classes是左表所以放在WHERE) SELECT c.name, count(s.name) AS num FROM classes c LEFT JOIN students s ON s.class_id = c.id WHERE c.name = '一班' GROUP BY c.name
5 thoughts on “MySQL LEFT JOIN / INNER JOIN 中 ON/WHERE 條件 建議規定用法”
SQL LEFT JOIN 把 NULL 欄位 替換成別的數值(補0) ~ IFNULL語法
SELECT fm.SID AS SID,fm.func_name AS Name,IFNULL(rf.role_sid,0) AS Eenabe
FROM func_main AS fm LEFT JOIN role_func AS rf
ON (fm.SID=rf.func_sid) AND (rf.role_sid=2)
IFNULL 支援SQL有: MySQL ,SQLite
MSSQL 要使用 ISNULL
MySQL ,SQLite ,MSSQL LEFT JOIN 把 NULL 欄位 替換成別的數值(補0)
超過 2個資料表 (多個表資料/多表/多資料表) SQL LEFT JOIN / INNER JOIN 實際範例:
SELECT DISTINCT a.set_sid,a.attribute_sid,a.category_sid,c.category_code,c.category_name,c.sort
FROM product_set_relation a JOIN product_data b
ON b.SID=a.product_sid AND b.del_flag='N' AND b.stop_flag='N'
JOIN product_category c ON c.SID=a.category_sid AND c.del_flag='N' AND c.stop_flag='N'
WHERE a.set_sid='{0}' ORDER BY c.sort;
參照上面範例 全部自己寫(確定會動)
第一段 13+12 = 25筆資料
第二段 (13*7)+12 = 103筆
SELECT t.SID,t.tableware_code,t.tableware_name,t.change_tableware_sid,p.product_sid,p.quantity,c.condiment_sid FROM tableware_data AS t
LEFT JOIN tableware_product_relation AS p ON t.SID=p.tableware_sid
LEFT JOIN tableware_condiment_relation AS c ON t.SID=c.tableware_sid
WHERE t.del_flag='N'