1

如何调整此 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

在此先感谢您的帮助!

4

2 回答 2

1

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

例如。

LEFT JOIN local_rev lr ON (u.user_id = lr.user_id) or (u.user_id IS NULL)
于 2013-05-08T17:44:02.760 回答
0

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

  • 每个 user_id 只有一条记录(注意所有子查询都有一个 GROUP BY user_id),因此对于用户表上的一条记录,您在子查询上有一条(或没有)记录
  • 独立连接(和计算的数据)不会被弄乱

-

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
于 2013-05-08T17:45:33.150 回答