简单的mysql查询计数失败

时间:2012-08-20 16:24:04

标签: mysql sql join

SELECT          
    count(t1.id) AS c1
FROM
    table2
    LEFT JOIN table1 AS t1 ON (t1.uid = table2.uid)
WHERE
    table2.mode = 'ls'
GROUP BY
    t1.id

c1 = 6 - > CORRECT!

SELECT          
    count(t2.id) AS c2
FROM
    table2
    LEFT JOIN table1 AS t2 ON (t2.pid = table2.id)
WHERE
    table2.mode = 'ls'
GROUP BY
    t1.id

c2 = 1 - > CORRECT!

SELECT          
    count(t1.id) AS c1,
    count(t2.id) AS c2
FROM
    table2
    LEFT JOIN table1 AS t1 ON (t1.uid = table2.uid)
    LEFT JOIN table1 AS t2 ON (t2.pid = table2.id)
WHERE
    table2.mode = 'ls'
GROUP BY
    t1.id

c1 = 6 - > CORRECT!

c2 = 6 - >错误!

如何在一个查询中请求两个计数,而不会得到错误的结果?

我需要在同一个表(table1)计算两个不同的请求。

所以,我正在为这两个请求使用别名。 (T1)。每个别名请求都可以正常工作。如果我在同一个查询中使用两者,我的结果都是错误的。

3 个答案:

答案 0 :(得分:1)

我相信您在完整查询中的问题是按功能分组。您按t.id分组,因此a1.id将根据您拥有的行数而有不同的计数。

我的意思是如果表t中有6行,那么对于表t,count将返回6;但是由于在表a上看起来是1比1的关系,表a中有6个匹配的行到表t中的6个匹配的行。这样

t.id = a.id 1 = 1 2 = 2 ......等等。

因此,您的计数是返回行数而不是您认为应该拥有的计数?我相信sum函数是你想在这里使用的。

答案 1 :(得分:1)

count()将为您提供查询返回的记录数。因为如果您删除了计数并将其替换为*,那么您将有6行,这两个计数都会给您6个。

你有什么理由不能使用两个子选择并返回每个子选择的结果吗?

所以:

SELECT subQ1.c1, subQ2.c2 FROM
    (SELECT count(t1.id) AS c1 FROM table2
        LEFT JOIN table1 AS t1 ON (t1.uid = table2.uid)
        WHERE table2.mode = 'ls') as subQ1, 
    (SELECT count(t2.id) AS c2 FROM table2
        LEFT JOIN table1 AS t2 ON (t2.pid = table2.id)
        WHERE table2.mode = 'ls') as SubQ2;

答案 2 :(得分:0)

你可以试试这个...但我不确定你要做什么。

SELECT (...)
    count(CASE WHEN t1.uid = t3.uid THEN t1.id ELSE NULL END) AS CBanz,
    count(CASE WHEN ta1.pid = t3.id THEN a1.id ELSE NULL END) AS CBanz1
FROM
    t0
    LEFT JOIN (...)
    LEFT JOIN t1 ON (t1.uid = t3.uid)
    LEFT JOIN t1 AS a1 ON (a1.pid = t3.id)
WHERE (...)