我想使用join而不是内联查询,但我能够提供的是给出错误的值。 请检查此链接 - http://www.sqlfiddle.com/#!2/57cad/9
它有2个单独的查询,它们提供正确的值和连接查询,结果不正确。
有人可以帮忙......
答案 0 :(得分:1)
此处显示的答案:SQLFiddle
您的查询可以在一些区域得到改善,这使得他们的JOIN更加明显。
在第一个查询中,更好的版本具有SELECT子句中列出的GROUP BY子句的列,并且您的HAVING子句(工作时)成为WHERE子句(IMO:最佳做法是仅在HAVING中使用聚合函数子句:)
SELECT usercode, ROUND(coalesce(sum(paymentamount)*0.99,0),2) AS payment
FROM accountpayments
WHERE usercode = 21
GROUP BY usercode;
您的第二个查询可以重写为JOIN(与子查询相对)
SELECT campaigns.usercode, ROUND(coalesce(sum(lmc_cds.total_spending),0),2) AS total_spending
FROM logsmaincontrols_campaigns_daily_stats AS lmc_cds
JOIN campaigns
ON campaigns.campcode = lmc_cds.campcode
WHERE campaigns.usercode = 21;
由于查询不共享任何表,我决定使用usercode作为JOINing列将查询作为派生表加入。
SELECT t1.usercode, t1.payment, t2.total_spending
FROM (SELECT usercode, ROUND(coalesce(sum(paymentamount)*0.99,0),2) AS payment
FROM accountpayments
WHERE usercode = 21
GROUP BY usercode) AS t1
JOIN (SELECT campaigns.usercode, ROUND(coalesce(sum(lmc_cds.total_spending),0),2) AS total_spending
FROM logsmaincontrols_campaigns_daily_stats AS lmc_cds
JOIN campaigns
ON campaigns.campcode = lmc_cds.campcode
WHERE campaigns.usercode = 21) AS t2
ON t1.usercode = t2.usercode;