简体   繁体   English

MySQL Join从左表中返回所有数据以及在右表中找到的所有数据

[英]MySQL Join returning ALL data from left table and whatever is found in right table

Brain bad. 脑子不好 Something isn't clicking that I know is probably simple. 我知道这很简单,这不是单击即可。 I'm trying my best to avoid a subquery but it may be unavoidable. 我正在尽力避免子查询,但这可能是不可避免的。

There are 11 records in the left table [ cards_types ] and between 1 and 11 records in the right table [ users_cards ]. 共有11条记录中左表[ cards_types ]和1之间和11条记录中右表[ users_cards I need to return all records from the left table and whatever is found in the right table. 我需要从左表以及在右表中找到的所有内容返回所有记录。 The only caveat to the right table is doing some IF / ELSE statements to return 0 values if it card_types . 右表的唯一警告是,如果执行card_types则执行一些IF / ELSE语句以返回0值。 id is not found in users_cards . id中找不到users_cards Also, there is a foreign key constraint on cards_types . 另外,在cards_types上有一个外键约束。 id => users_cards . id => users_cards type_id (if it matters). type_id (如果有关系)。

Query 询问

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

You are currently using an INNER JOIN , change it to a LEFT JOIN . 您当前正在使用INNER JOIN ,将其更改为LEFT JOIN I also moved your WHERE clause filters to the JOIN so you will return all rows from cards_type . 我也将您的WHERE子句过滤器移到了JOIN因此您将从cards_type返回所有行。 If you leave the filters in the WHERE clause, then it will act like an INNER JOIN : 如果将过滤器保留在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

try with left join like that 尝试像这样的左连接

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM