John
John

Reputation: 101

How can I adjust a JOIN clause so that rows that have columns with NULL values are returned in the result?

How can I adjust this JOIN clause so that rows with a NULL value for the CountLocId or CountNatId columns are returned in the result?

In other words, if there is no match in the local_ads table, I still want the user's result from the nat_ads table to be returned -- and vice-versa.

SELECT u.franchise, CountLocId, TotalPrice, CountNatId, TotalNMoney, (
TotalPrice + TotalNMoney
)TotalRev
FROM users u
LEFT JOIN local_rev lr ON u.user_id = lr.user_id
LEFT JOIN (

SELECT lrr_id, COUNT( lad_id ) CountLocId, SUM( price ) TotalPrice
FROM local_ads
GROUP BY lrr_id
)la ON lr.lrr_id = la.lrr_id
LEFT JOIN nat_rev nr ON u.user_id = nr.user_id
INNER JOIN (

SELECT nrr_id, COUNT( nad_id ) CountNatId, SUM( tmoney ) TotalNMoney
FROM nat_ads
WHERE MONTH =  'April'
GROUP BY nrr_id
)na ON nr.nrr_id = na.nrr_id
WHERE lr.month =  'April'
AND franchise !=  'Corporate'
ORDER BY franchise

Thanks in advance for your help!

Upvotes: 1

Views: 57

Answers (2)

Saic Siquot
Saic Siquot

Reputation: 6513

Use this template, as it ensures that :

  • you have only one record per user_id (notice all subquerys have a GROUP BY user_id) so for one record on user table you have one (or none) record on subquery
  • independent joins (and calculated data) are not messed togeder

-

SELECT u.franchise, one.CountLocId, one.TotalPrice, two.CountNatId, two.TotalNMoney, (COALESCE(one.TotalPrice,0) + COALESCE(two.TotalNMoney,0)) TotalRev
FROM users u

LEFT JOIN (
    SELECT x.user_id, sum(xORy.whatever) as TotalPrice, count(xORy.whatever) as CountLocId
    FROM   x                             -- where   x is  local_rev or local_ads   I dont know
    LEFT JOIN  y  on x.... = y....       -- where   y is  local_rev or local_ads   I dont know
    GROUP BY  x.user_id
) as one   on u.user_id  = one.user_id

LEFT JOIN (
    SELECT x.user_id, sum(xORy.whatever) as TotalNMoney, count(xORy.whatever) as CountNatId
    FROM   x                             -- where   x is  nat_rev or nat_ads   I dont know
    LEFT JOIN  y  on x.... = y....       -- where   y is  nat_rev or nat_ads   I dont know
    GROUP BY  x.user_id
) as two   on u.user_id  = two.user_id

Upvotes: 0

Ankush Jain
Ankush Jain

Reputation: 1527

try the following in where clause while making a left join. This will take all rows from right table with matched condition

eg.

LEFT JOIN local_rev lr ON (u.user_id = lr.user_id) or (u.user_id IS NULL)

Upvotes: 1

Related Questions