0
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 -> 正确!

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 -> 正确!

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 -> 正确!

c2 = 6 -> 错误!

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

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

所以,我对这两个请求都使用了别名。(t1)。每个别名请求都可以单独工作。如果我在同一个查询中同时使用两者,我会得到错误的结果。

4

3 回答 3

1

count() will get you the number of records that are returned by your query. Since if you removed the counts and replaced it with * you would have 6 rows both of those counts are giving you 6.

Is there any reason why you cant use two sub selects and return the result of each of those?

So:

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;
于 2012-08-20T18:27:16.217 回答
1

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

我的意思是如果表 t 中有 6 行,那么 count 将为表 t 返回 6;而且由于表 a 上看起来存在 1 对 1 的关系,因此表 a 中有 6 个匹配行与表 t 中的 6 个匹配行。这样

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

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

于 2012-08-20T17:47:33.823 回答
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 (...)
于 2012-08-20T16:32:30.270 回答