[英]MySQL SELECT all from first table and join matched data from second table with specific where clause for second table filter
[英]LEFT OUTER JOIN keep all matched results from first table use where just for second table
當我嘗試在此處執行以下mysql查詢時,我不會在WHERE子句中返回所有記錄ID。
我正在嘗試做的是:
JOIN第二個表(websites_thumbs)由表1的website_salt記錄結果
按表1中記錄的鹽,也按父網站中的鹽($ parent_salt)
SUM投票並返回記錄結果(如果在第二個表中未找到結果,則返回0)
ID 119和ID 250在第二張表中具有投票結果,其他人則沒有。 我遇到的問題是,當我執行查詢時,它僅返回記錄1,119和250,而其他ID已存在,但未返回?
查詢:
// VxZQ85cByb98wUx0f3 =>來自另一個查詢的母鹽(頁面數據查詢)
SELECT
SUM(CASE t.thumb when 1 then 1 else 0 end) as thumbs_up,
SUM(CASE t.thumb when -1 then 1 else 0 end) as thumbs_down,
w.*, t.*
FROM websites as w
LEFT OUTER JOIN websites_thumbs AS t
ON t.similar_website_salt = w.salt AND t.website_salt = 'VxZQ85cByb98wUx0f3'
WHERE w.id IN ('1', '20', '31', '4', '199', '250', '633953')
GROUP BY t.similar_website_salt
第一張桌子
第二張桌子
執行結果
希望有人可以幫助我!
謝謝
代替LEFT OUTER JOIN
嘗試INNER JOIN
。 另外,請勿在IN
子句中使用'
。 最后,只是因為我很挑剔,所以我更改了您的JOIN
順序:
SELECT
SUM(CASE t.thumb when 1 then 1 else 0 end) as thumbs_up,
SUM(CASE t.thumb when -1 then 1 else 0 end) as thumbs_down,
w.*, t.*
FROM websites as w
INNER JOIN websites_thumbs AS t
ON w.salt = t.similar_website_salt AND t.website_salt = 'VxZQ85cByb98wUx0f3'
WHERE w.id IN (1, 20, 31, 4, 199, 250, 633953)
GROUP BY t.similar_website_salt
不查看表模式很難說,因此,如果您想將其中的一些內容扔掉,將會很有幫助。
您對GROUP BY
使用將消除所有具有similar_website_salt
為空的similar_website_salt
。 您需要將null
值更改為其他值(例如,空字符串),然后按該值分組。 請注意,添加了COALESCE
有兩行:
SELECT
SUM(CASE t.thumb when 1 then 1 else 0 end) as thumbs_up,
SUM(CASE t.thumb when -1 then 1 else 0 end) as thumbs_down,
w.*, t.*,
COALESCE(t.similar_website_salt, '')
FROM websites as w
LEFT OUTER JOIN websites_thumbs AS t
ON t.similar_website_salt = w.salt AND t.website_salt = 'VxZQ85cByb98wUx0f3'
WHERE w.id IN ('1', '20', '31', '4', '199', '250', '633953')
GROUP BY COALESCE(t.similar_website_salt, '')
並非所有記錄在第二個表中都有子記錄,因此我們不能GROUP BY t.similar_website_salt並將記錄保留在結果集中而沒有該值。
SELECT
SUM(CASE t.thumb when 1 then 1 else 0 end) as thumbs_up,
SUM(CASE t.thumb when -1 then 1 else 0 end) as thumbs_down,
w.*, t.*
FROM websites as w
LEFT OUTER JOIN websites_thumbs AS t
ON t.similar_website_salt = w.salt AND t.website_salt = 'VxZQ85cByb98wUx0f3'
WHERE w.id IN ('1', '20', '31', '4', '199', '250', '633953')
//GROUP BY t.similar_website_salt
GROUP BY w.id <-- this does the trick
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.