左连接产生错误的结果

时间:2013-12-27 11:48:30

标签: mysql sql

我有三张桌子: ab,a和b 表a和b应该具有相同touid的多次出现。

SELECT * FROM ab
tourid  tourname    
------  ------------
   100  hundred     
   110  one ten     
   120  one twenty 


 select * from a;
imageid  tourid  filesize  
-------  ------  ----------
      1     100          10
      2     100          20

SELECT * FROM b
   uid  tourid  filesize  
------  ------  ----------
     5     100           5

sql查询:

SELECT 
a.tourid, 
SUM(a.filesize) AS a_sum,
SUM(b.filesize) AS b_sum
FROM ab
LEFT JOIN a ON a.tourid=ab.tourid
LEFT JOIN b ON b.tourid=ab.tourid
WHERE ab.tourid=100

将结果显示为:

tourid   a_sum   b_sum  
------  ------  --------
   100      30        10

但结果应该是:

tourid   a_sum   b_sum  
------  ------  --------
   100      30        5

b_sum列的结果是错误的

3 个答案:

答案 0 :(得分:3)

在第一个表格中,您有一行:

tourid  tourname 
 100  hundred     

加入一个表将产生两行:

tourid  tourname    imaageid  filesize
 100    hundred     1          10
 100    hundred     2          20

加入b表将保留2行:

 tourid  tourname    imaageid  filesize   uid   filesize
 100    hundred     1          10         5       5
 100    hundred     2          20         5       5

好的查询是:

select tourid, sum_a, sum_b 
from ab
left join (select tourid, sum(filesize) as sum_a from a group by tourid) a on ab.tourid = a.tourid
left join (select tourid, sum(filesize) as sum_b from b group by tourid) b on ab.tourid = b.tourid

答案 1 :(得分:1)

你需要添加GROUP BY ab.tourid来克服重复,有重复的结果因此你得到的总和是两次

SELECT 
a.tourid, 
SUM(a.filesize) AS a_sum,
SUM(b.filesize) AS b_sum
FROM ab
LEFT JOIN a ON a.tourid=ab.tourid
LEFT JOIN b ON b.tourid=ab.tourid
WHERE ab.tourid=100
GROUP BY ab.tourid

答案 2 :(得分:1)

计数是正确的:由于您一次加入两个表,聚合前的结果将如下所示:

tourid  a.filesize b.filesize
------  ---------- ----------
  100         10          5
  100         20          5

b中的每个联接行都会获得a的同一行。

当你总计a.filesize时,你得到30;当你总计b.filesize时,你得到10,解释结果。

您可以在没有连接或聚合的情况下获得您希望的结果 - 简单的子查询就足够了:

SELECT
    100
,   (SELECT SUM(filesize) FROM a WHERE tourid=100) as sum_a
,   (SELECT SUM(filesize) FROM b WHERE tourid=100) as sum_a