来自两个连接表的mySQL SELECT,子查询中包含数据总和

时间:2017-04-06 08:12:37

标签: mysql if-statement select sum subquery

我有一张像这样的表“schLoc”

------------------------
| id | ... | ... | ... |
------------------------
| 1  | ... | ... | ... |
| 2  | ... | ... | ... |
| 3  | ... | ... | ... |
| 4  | ... | ... | ... |
| 5  | ... | ... | ... |
| .. | ... | ... | ... |
------------------------

和像这样的“schLocDett”之类的另一个表,其中schLoc.id = schLocDett.idDoc

-------------------------------
| idDoc | qta | ... | merce   |
-------------------------------
| 1     |  1  | ... | fattLoc |
| 1     |  1  | ... | fattSrv | 
| 2     |  3  | ... | fattLoc | 
| 2     |  2  | ... | notcSrv | 
| 2     |  2  | ... | fattSrv | 
| 3     |  5  | ... | fattSrv | 
| 3     |  3  | ... | notcSrv | 
| 3     |  3  | ... | fattLoc | 
| 3     |  7  | ... | fattLoc | 
| 4     |  5  | ... | notcSrv | 
| 4     |  4  | ... | fattSrv | 
| 4     |  1  | ... | fattSrv | 
| 5     |  1  | ... | notcSrv | 
| ...   | ... | ... | ....... | 
-------------------------------

我想列出完整的schLoc列表,并且每个id都是qta的总和,但仅限于merce = fattLoc。如果不存在,则总和将为0。 这是我期望的结果

---------------------------
| id | sumQta | ... | ... |
------------------------
| 1  | 1      | ... | ... |
| 2  | 3      | ... | ... |
| 3  | 10     | ... | ... |
| 4  | 0      | ... | ... |
| 5  | 0      | ... | ... |
| .. | ...    | ... | ... |
---------------------------

我试着用这个:

SELECT TOT.sumQta, TAB.*, 
FROM schLoc AS TAB, schLocDett AS DETT,
    (SELECT idDoc, SUM(qta) AS sumQta 
     FROM schLocDett 
     WHERE merce='fattLoc' 
     GROUP BY idDoc) AS TOT
WHERE TAB.id>0 
  AND TAB.id=DETT.idDoc 
  AND TAB.id=TOT.idDoc

但未获得Id 4和5

欢迎任何建议

2 个答案:

答案 0 :(得分:1)

SELECT TAB.*, COALESCE(TOT.sumQta, 0) AS sumQta
FROM schLoc TAB
LEFT JOIN
(
    SELECT idDoc, SUM(qta) AS sumQta
    FROM schLocDett
    WHERE merce = 'fattLoc'
    GROUP BY idDoc
) TOT
    ON TAB.id = TOT.idDoc

<强>输出:

enter image description here

在这里演示:

Rextester

答案 1 :(得分:1)

您可以将LEFT JOINIFNULL一起使用,例如:

SELECT loc.id, SUM(IFNULL(det.qta, 0)) AS sum
FROM schLoc loc LEFT JOIN schLocDett det ON loc.id = det.idDoc
WHERE det.merce = 'fattLoc'
GROUP BY loc.id;