mysql计数表行与count子表行

时间:2018-03-27 11:40:46

标签: mysql sql

我有三张桌子。 a> b> c表。我希望彼此分开总计并优化查询。我的查询没有给出真实的数字。

TABLE:a

a
-----------
id
no
create_time

TABLE:b

b
-----------
id
no

TABLE:c

c
-----------
id
b_id

此查询未提供真实的计数

SELECT
    DATE( a.create_time ) AS date,
    COUNT( a.id ) AS total_a,
    COUNT( b.id ) AS total_b,
    COUNT( c.id ) AS total_c 
FROM
    `a`
    LEFT JOIN `b` ON `a`.`no` = `b`.`no`
    LEFT JOIN `c` ON `b`.`id` = `c`.`b_id` 
WHERE
    ( `a`.`status` = 1 ) 
GROUP BY
    DATE( a.create_time ) 
ORDER BY
    `date` DESC 
    LIMIT 20

1 个答案:

答案 0 :(得分:3)

对于右侧的每个匹配行,A left join重复左侧的每一行。所以你获得的行数比原来的多。

一个简单的解决方法是只计算唯一标识符:

SELECT
    DATE( a.create_time ) AS date,
    COUNT( DISTINCT a.id ) AS total_a,
    COUNT( DISTINCT b.id ) AS total_b,
    COUNT( DISTINCT c.id ) AS total_c