MYSQL:JOIN使SUM加倍

时间:2011-04-15 21:31:04

标签: mysql join sum

这应该很容易。相信我,我已经研究了几个小时了。我的问题:

SELECT not_piece.pid, part.name AS 'Part Name', SUM(qty_left) AS 'In Stock'
FROM not_piece 
JOIN part ON not_piece.pid = part.pid 
GROUP BY part.name;

只有两个表,not_piece和part。

select qty_left 
from not_piece 
where pid='M-MP-007r8'; 

返回5.

由于part.name在parts表中出现两次(没关系),总和为10,而不是5。

如何在不加倍的情况下进行此连接?

感谢。

2 个答案:

答案 0 :(得分:2)

SELECT t.pid, p.name AS 'Part Name', t.InStock AS 'In Stock'
    FROM (SELECT pid, SUM(qty_left) AS InStock
              FROM not_piece
              GROUP BY pid) t
        INNER JOIN part p
            ON t.pid = p.pid

答案 1 :(得分:1)

使用GROUP BY,尝试按主键pid进行分组:

SELECT not_piece.pid, part.name AS 'Part Name', SUM(qty_left) AS 'In Stock'
FROM not_piece 
JOIN part ON not_piece.pid = part.pid 
GROUP BY part.pid;