[英]MySQL Join returning ALL data from left table and whatever is found in right table
腦子不好 我知道這很簡單,這不是單擊即可。 我正在盡力避免子查詢,但這可能是不可避免的。
共有11條記錄中左表[ cards_types
]和1之間和11條記錄中右表[ users_cards
。 我需要從左表以及在右表中找到的所有內容返回所有記錄。 右表的唯一警告是,如果執行card_types
則執行一些IF / ELSE語句以返回0值。 id
中找不到users_cards
。 另外,在cards_types
上有一個外鍵約束。 id
=> users_cards
。 type_id
(如果有關系)。
詢問
SELECT
t.id,
t.slug,
t.label AS type_label,
t.points AS point_value,
IF (c.mtg_id IS NULL, 0, c.mtg_id) AS mtg_id,
IF (c.label IS NULL, 0, c.label ) AS card_label,
IF (uc.points IS NULL, 0, uc.points ) AS card_score
FROM cards_types t
JOIN users_cards uc
ON uc.type_id = t.id
JOIN cards c
ON c.id = uc.card_id
WHERE uc.user_id = 1
AND uc.season_id = 1
ORDER BY t.priority ASC
您當前正在使用INNER JOIN
,將其更改為LEFT JOIN
。 我也將您的WHERE
子句過濾器移到了JOIN
因此您將從cards_type
返回所有行。 如果將過濾器保留在WHERE
子句中,則其作用類似於INNER JOIN
:
SELECT
t.id,
t.slug,
t.label AS type_label,
t.points AS point_value,
COALESCE(c.mtg_id, 0) AS mtg_id,
COALESCE(c.label, 0) AS card_label,
COALESCE(uc.points, 0) AS card_score
FROM cards_types t
LEFT JOIN users_cards uc
ON uc.type_id = t.id
AND uc.user_id = 1 -- < -- move the where filters here
AND uc.season_id = 1
LEFT JOIN cards c
ON c.id = uc.card_id
ORDER BY t.priority ASC
嘗試像這樣的左連接
SELECT
t.id,
t.slug,
t.label AS type_label,
t.points AS point_value,
COALESCE(c.mtg_id, 0) AS mtg_id,
COALESCE(c.label, 0) AS card_label,
COALESCE(uc.points, 0) AS card_score
FROM cards_types t
LEFT JOIN users_cards uc
ON uc.type_id = t.id
AND uc.user_id = 1
AND uc.season_id = 1
LEFT JOIN cards c
ON c.id = uc.card_id
ORDER BY t.priority ASC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.