查询具有多个连接和每个表的多个计数的forumaltion

时间:2012-08-21 10:19:04

标签: mysql join count

嘿伙计们希望你能帮助我。

我正在尝试进行查询,以便在三个不同的表中有一个带有外键的主表。现在我想分别计算所有3个表中的条目。这是我到目前为止所做的,希望你们能帮助我解决它。

SELECT box_code.id, count( box_code_unused.id ) AS total, count( box_code_used.id ) AS total2, count( box_code_expired.id ) AS total3
FROM box_code
JOIN box_code_used ON box_code_used.box_code_id = box_code.id
JOIN box_code_unused ON box_code_unused.box_code_id = box_code.id
JOIN box_code_expired ON box_code_expired .box_code_id = box_code.id
GROUP BY box_code.id

如果我只计算一个表中的条目,这种方法会起作用,但因为我从3个表计数它是不正确的。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您可能会count distinct出现ID:

SELECT box_code.id, 
       count(distinct box_code_unused.id ) AS total, 
       count(distinct box_code_used.id ) AS total2, 
       count(distinct box_code_expired.id ) AS total3
FROM box_code
LEFT JOIN box_code_used ON box_code_used.box_code_id = box_code.id
LEFT JOIN box_code_unused ON box_code_unused.box_code_id = box_code.id
LEFT JOIN box_code_expired ON box_code_expired .box_code_id = box_code.id
GROUP BY box_code.id

答案 1 :(得分:1)

使用如下子查询:

SELECT box_code.id, 
    (SELECT COUNT(*) FROM box_code_used b1 WHERE b1.box_code_id = box_code.id) AS total1,
    (SELECT COUNT(*) FROM box_code_unused b2 WHERE b2.box_code_id = box_code.id) AS total2,
    (SELECT COUNT(*) FROM box_code_expired b3 WHERE b3.box_code_id = box_code.id) AS total3
FROM box_code

答案 2 :(得分:0)

我认为你可以使用正确的加入。这样,它将包括一个表中不可用但在其他表中可用的记录。