我很困惑!我有3个表,分别给我我正在寻找的结果。当我加入他们(尝试加入,联合,左联接,子查询)时,我得到了偏差的结果。
表1:
SELECT DISTINCT JB.job_id, AR.job_id as jid, SUM(AR.ar_payment_amount) AS sum,
JB.marketing_campaign FROM job_tbl JB LEFT JOIN ar_payment_tbl AR ON JB.job_id =
AR.job_id WHERE JB.marketing_campaign != '' AND FROM_UNIXTIME(AR.ar_payment_date,'%Y') =
YEAR(NOW()) GROUP BY JB.marketing_campaign ORDER BY sum DESC LIMIT 10
这给了我正在寻找的结果(只显示了这个例子的一个结果)
[job_id] => 551
[jid] => 551
[sum] => 124440.97024536133
[marketing_campaign] => Roto Rooter
表2:
SELECT DISTINCT JB.job_id, AP.job_id, SUM(price) AS price, AP.vendor FROM job_tbl JB
LEFT JOIN ap_tbl AP ON JB.job_id = AP.job_id WHERE AP.marked_as_paid = 1 AND
AP.activity = 'Commission' AND FROM_UNIXTIME(AP.payment_date,'%Y') = YEAR(NOW()) GROUP
BY vendor ORDER BY price DESC LIMIT 10
这给了我正在寻找的结果......
[job_id] => 551
[price] => 5700
[vendor] => 436
现在当我加入他们时,我得到了不同的结果
SELECT DISTINCT JB.job_id, AR.job_id as arid, AP.job_id as apid,
SUM(AR.ar_payment_amount) AS sum, SUM(AP.price) AS price, JB.marketing_campaign FROM
job_tbl JB LEFT JOIN ap_tbl AP ON JB.job_id = AP.job_id AND AP.marked_as_paid = 1 AND
AP.activity = 'Commission' LEFT JOIN ar_payment_tbl AR ON JB.job_id = AR.job_id AND
FROM_UNIXTIME(AR.ar_payment_date,'%Y') = YEAR(NOW()) WHERE AP.price != '' AND
AR.ar_payment_amount != '' AND JB.marketing_campaign != '' GROUP BY
JB.marketing_campaign ORDER BY sum DESC LIMIT 10
以下是我得到的结果
[job_id] => 551
[arid] => 551
[apid] => 551
[sum] => 130507.02011108398
[price] => 8200
[marketing_campaign] => Roto Rooter
以及结果应该是
[job_id] => 551
[arid] => 551
[apid] => 551
[sum] => 124440.97024536133
[price] => 5700
[marketing_campaign] => Roto Rooter
任何帮助将不胜感激,这个项目上周五到期! ; - )
答案 0 :(得分:0)
试试这个 - 我认为JOIN
条件和GROUP BY
存在问题:
SELECT
JB.job_id,
AR.job_id as arid,
AP.job_id as apid,
JB.marketing_campaign,
SUM(AR.ar_payment_amount) AS `sum`,
SUM(AP.price) AS price
FROM job_tbl JB
LEFT JOIN ap_tbl AP ON JB.job_id = AP.job_id
LEFT JOIN ar_payment_tbl AR ON JB.job_id = AR.job_id
WHERE
AP.marked_as_paid = 1
AND AP.activity = 'Commission'
AND FROM_UNIXTIME(AR.ar_payment_date,'%Y') = YEAR(NOW())
AND AP.price != ''
AND AR.ar_payment_amount != ''
AND JB.marketing_campaign != ''
GROUP BY 1,2,3,4
ORDER BY `sum` DESC LIMIT 10