Tuesday 4 September 2018

Mysql Left Join does not work

I wrote following query

SELECT
   us.Id as Id, us.Name as Name,
   SUM(CASE WHEN c.isPublish = 0 THEN 1 ELSE 0 END) AS PendingCoupons,
   SUM(CASE WHEN c.isPublish = 1 and convert(date,c.PublishedDate,101) >=  convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS ApprovedCouponsToday,
   SUM(CASE WHEN c.isPublish = 0 and convert(date,c. CreateDate, 101) = convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS PendingCouponsToday,
   SUM(CASE WHEN c.isPublish = 1 THEN 1 ELSE 0 END) AS ApprovedCoupons,
   SUM(CASE WHEN c.isPublish = 1 and c.Userid = us.Id and convert(date, c.PublishedDate, 101) >= convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS ApprovedByUserToday,
   SUM(CASE WHEN c.isPublish = 1 and c.Userid = us.Id THEN 1 ELSE 0 END) AS ApprovedByUser,
   SUM(CASE WHEN c.ReviewVerify = 1 and convert(date, c.PublishedDate, 101) >= convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS ProcessToday,
   COUNT(*) AS Total
FROM
   Users AS us
LEFT JOIN
   Coupon c ON Userid = us.Id
GROUP BY
   us.Name , us.Id

and I have following two tables
and after running above query the result is always this
Is there any error in this query , because its always returning me count " 0 " and I have almost 100 coupons on every user but its not showing

It would seem that since RIGHT JOIN works and gives correct answers (and probably a bogus user id) while a LEFT JOIN doesn't give any results related to coupons at all, the coupons are registered on a non existing user.
LEFT JOIN demands that data exists in the left part of the table that possibly exists in the right side, while RIGHT JOIN does the reverse. In other words, data exists in your rightmost table (coupon) that doesn't have any connection to the left side (user)

0 comments:

Post a Comment