如何调整JOIN子句,以便在结果中返回具有NULL值列的行?

时间:2013-05-08 17:40:14

标签: mysql join

如何调整此JOIN子句,以便在结果中返回CountLocId或CountNatId列具有NULL值的行?

换句话说,如果local_ads表中没有匹配项,我仍然希望返回nat_ads表中用户的结果 - 反之亦然。

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

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

在进行左连接时尝试以下where子句。这将从右表中获取具有匹配条件的所有行

例如

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

答案 1 :(得分:0)

使用此模板,因为它可以确保:

  • 每个user_id只有一条记录(注意所有subquerys都有GROUP BY user_id)所以对于用户表上的一条记录,你在子查询上有一条(或没有)记录
  • 独立连接(和计算数据)不是混乱的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