Jason Oakley
Jason Oakley

Reputation: 91

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]. 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

Upvotes: 0

Views: 417

Answers (2)

echo_Me
echo_Me

Reputation: 37253

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

Upvotes: 0

Taryn
Taryn

Reputation: 247810

You are currently using an INNER JOIN, change it to a LEFT JOIN. I also moved your WHERE clause filters to the JOIN so you will return all rows from cards_type. If you leave the filters in the WHERE clause, then it will act like an 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

Upvotes: 3

Related Questions