Question

This request return items from tcredit higher than the sum of them in the tcredit_order items. But I doesn't return the items that are not in the tcredit_order. I tested other ways like subqueries but it doesn't work and this seems more simple.

SELECT * FROM tcredit
LEFT JOIN tcredit_order ON tcredit.id_credit=tcredit_order.id_credit
GROUP BY tcredit.id_credit
HAVING tcredit.credit > SUM(tcredit_order.credit)
ORDER BY tcredit.date_limit ASC
Was it helpful?

Solution

It is a common trap: as soon as you add a WHERE- about a LEFT JOINed table, you logically and implicitely make it an inner join as long as you do not add a hint about NULL.

SELECT * FROM tcredit
LEFT JOIN tcredit_order ON tcredit.id_credit=tcredit_order.id_credit
GROUP BY tcredit.id_credit
HAVING (tcredit.credit > SUM(tcredit_order.credit) or (SUM(tcredit_order) is null))  
ORDER BY tcredit.date_limit ASC

That should fix the problem. Remember: 1 > 0 is true, but 1 > NULL is NULL and not true.

Following the Comment, coalesce is a bit cooler (I usually use it for longer chains only).

HAVING (tcredit.credit > COALESCE(SUM(tcredit_order.credit),0))

Or if you're afraid your coworkers might not know it simply IFNULL

HAVING (tcredit.credit > IFNULL(SUM(tcredit_order.credit),0))

OTHER TIPS

This request return items from tcredit higher than the sum of them in the tcredit_order items.

There are 2 possibilities one get everything from the table tcredit where the credit is greater than sum of credit on the other table and the query should be as

select 
tc.* from tcredit tc
left join tcredit_order tco on tco.id_credit = tc.id_credit
group by tc.id_credit 
having  tc.credit > coalesce(sum(tco.credit),0)

2nd only data which are present in the first and the second table and in this case

select tc.* from tcredit tc
inner join
(
  select 
  id_credit,
  coalesce(sum(credit),0) as tot
  from tcredit_order
  group by id_credit
)tco
on tco.id_credit = tc.id_credit
where tc.credit > tco.tot
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top