0

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]. 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.id is not found in users_cards. Also, there is a foreign key constraint on cards_types.id => users_cards.type_id (if it matters).

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
4

2 回答 2

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
于 2013-01-16T23:37:46.080 回答
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
于 2013-01-16T23:38:52.533 回答