SQL - 使用sum的多个连接不会给出预期的结果

时间:2017-06-19 01:11:41

标签: sql

这是我的要求

SELECT j.* ,
    c.name as client_name ,
    s.name as supplier_name,
    s.ID as supplier_id ,
    mt.* ,
    SUM(pb.require_followup) as nb_followup,
    SUM(ws.worked_time) as hours_on_job,
    SUM(iv.total) as total_price,
    SUM(iv.hour_expected) as hours_planned,
    j.ID as ID 

FROM $wpdb->posts j
LEFT JOIN ".Job::$META_TABLE." mt ON mt.post_id = j.ID 
LEFT JOIN ".Job::$LINK_TABLE_JOB_CONTACT." l1 ON l1.job_id = j.ID 
LEFT JOIN ".Contact::$TABLE_NAME." c ON  c.ID = l1.contact_id
LEFT JOIN ".Supplier::$TABLE_NAME." s ON  s.ID = c.supplier_id
LEFT JOIN ".Problem::$TABLE_NAME." pb ON  pb.job_id = j.ID
LEFT JOIN ".Worksheet::$TABLE_NAME." ws ON  ws.job_id = j.ID
LEFT JOIN ".Invoice::$TABLE_NAME." iv ON  iv.job_id = j.ID

WHERE j.post_status = 'publish' 
    AND j.post_type = 'job'
    ".implode(' ',$where_condition)."
GROUP BY j.ID
ORDER BY j.post_date DESC

问题是当我LEFT JOIN其他表时SUM的结果是错误的。 例如,第53行为{nb_followup而不是105

提供1

如果此请求仅通过删除最后2个LEFT JOIN返回正确的结果:LEFT JOIN ".Worksheet::$TABLE_NAME." ws ON ws.job_id = j.IDLEFT JOIN ".Invoice::$TABLE_NAME." iv ON iv.job_id = j.ID

SELECT j.* ,
    c.name as client_name ,
    s.name as supplier_name,
    s.ID as supplier_id ,
    mt.* ,
    SUM(pb.require_followup) as nb_followup,
    j.ID as ID 

FROM $wpdb->posts j
LEFT JOIN ".Job::$META_TABLE." mt ON mt.post_id = j.ID 
LEFT JOIN ".Job::$LINK_TABLE_JOB_CONTACT." l1 ON l1.job_id = j.ID 
LEFT JOIN ".Contact::$TABLE_NAME." c ON  c.ID = l1.contact_id
LEFT JOIN ".Supplier::$TABLE_NAME." s ON  s.ID = c.supplier_id
LEFT JOIN ".Problem::$TABLE_NAME." pb ON  pb.job_id = j.ID


WHERE j.post_status = 'publish' 
    AND j.post_type = 'job'
    ".implode(' ',$where_condition)."
GROUP BY j.ID
ORDER BY j.post_date DESC

同样仅删除LEFT JOIN ".Invoice::$TABLE_NAME." iv ON iv.job_id = j.ID将为行53提供15

恢复

完整请求105 - >错误应该是1

删除最后一次加入15 - >错误应该是1

删除最后2个联接人1 - >正确

1 个答案:

答案 0 :(得分:0)

您需要在加入之前计算SUM()s,否则行会因连接而相乘,这反过来会导致求和错误。 e.g。

SELECT
      j.ID as ID 
    , pb.nb_followup
FROM $wpdb->posts j
LEFT JOIN (select pb.job_id, SUM(pb.require_followup) as nb_followup from ".Problem::$TABLE_NAME." pb GROUP BY pb.job_id) pb ON  pb.job_id = j.ID

您面临的另一个问题是MySQL允许“lazy syntax”用于分组。不要使用这种惰性语法,否则会出现意外错误/错误。很容易避免,REPEAT group by子句中的select子句的每一列UNLESS该列使用的是聚合函数,如SUM(),COUNT(),MIN(),MAX()等等.eg < / p>

select  a.col1, b.col2, c.col3 , sum(d.col4)
from a
inner join b on a.id = b.aid
inner join c on b.id = c.bid
inner join d on c.id = d.cid
group by a.col1, b.col2, c.col3