Skip to content
Advertisement

SQL Join : how to show the first table data even the 2nd table condition false

I want to keep show my first table data even the second table condition is false.

Table 1

---------------------------
  ID  | Name
---------------------------
  1   | Panda
  2   | Tiger
---------------------------

Table 2

---------------------------
  ID  | Date       | Weight
---------------------------
  1   | 2019-02-01 |   30
  1   | 2019-02-10 |   31
---------------------------

I expect data like this when I asking data for the date = ‘2019-02-18’ and ID = 1

-------------------------------------
  ID  | Name  | Date       |  Weight
-------------------------------------
  1   | Panda | 2019-02-18 |    0
-------------------------------------

Advertisement

Answer

Are you looking for a simple LEFT JOIN, as follows ?

SELECT t1.id, t1.name, date '2019-02-18', COALESCE(t2.weight, 0) weight
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id AND t2.date = date '2019-02-18'
WHERE t1.id = 1

The LEFT JOIN optionaly searches for record in table2 with the given date criteria. When no record match, t2.weight is NULL : COALESCE() picks up this situation, and returns 0 instead.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement