MySQL Join返回左表中的所有数据以及右表中的任何数据

时间:2013-01-16 23:34:25

标签: php mysql join

大脑不好。我不知道点击的东西可能很简单。我正尽力避免使用子查询,但这可能是不可避免的。

左表[cards_types]中有11条记录,右表[users_cards]中有1到11条记录。我需要返回左表中的所有记录以及右表中的所有记录。对于右表的唯一警告是,如果在card_types中找不到id users_cards,则执行一些IF / ELSE语句以返回0值。此外,cards_types上存在外键约束。id => users_cardstype_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

2 个答案:

答案 0 :(得分:3)

您目前正在使用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

答案 1 :(得分:0)

尝试使用左连接

 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