Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL LEFT JOIN not working properly

I have 2 tables:

T1 (id, flag1)
T2 (id, amount, date, flag2, t1_id);

I have the following query:

SELECT T1.id, ROUND(COALESCE(SUM(T2.amount), 0), 2) AS spent_amount
FROM T1
LEFT JOIN T2 ON T2.t1_id = T1.id
WHERE T2.date <= '2014-01-01' AND T2.flag2 = 't' AND T1.flag1 = 't'
GROUP BY T1.id

The problem is that I want to have a row in the result such as: id = 123, spent_amount = 0 in case where I have an entrance in T1, but it has no connected rows in T2.

like image 319
uno_ordinary Avatar asked Aug 07 '14 15:08

uno_ordinary


1 Answers

Having a WHERE clause on your T2 it will filter out all NULLS:

SELECT T1.id, ROUND(COALESCE(SUM(T2.amount), 0), 2) AS spent_amount 
FROM T1 
LEFT JOIN T2 
    ON T2.t1_id = T1.id 
    AND T2.date <= '2014-01-01' 
    AND T2.flag2 = 't' 
WHERE T1.flag1 = 't'
like image 172
Giannis Paraskevopoulos Avatar answered Nov 04 '22 03:11

Giannis Paraskevopoulos