MySQL count()问题

时间:2009-09-30 15:52:22

标签: sql mysql count

设定:

create table main(id integer unsigned);
create table test1(id integer unsigned);
create table test2(id integer unsigned);

insert into main(id) value(1);
insert into test1(id) value(1);
insert into test1(id) value(1);
insert into test2(id) value(1);    
insert into test2(id) value(1);
insert into test2(id) value(1);

使用:

   select main.id, 
          count(test1.id),
          count(test2.id) 
     from main
left join test1 on main.id=test1.id
left join test2 on main.id=test2.id
group by main.id;

...返回:

+------+-----------------+-----------------+
| id   | count(test1.id) | count(test2.id) |
+------+-----------------+-----------------+
|    1 |               6 |               6 |
+------+-----------------+-----------------+

如何获得1 2 3的预期结果?

修改

解决方案应该是可扩展的,我将来会查询有关main.id的多个count()信息。

5 个答案:

答案 0 :(得分:1)

不是最佳,但有效:

select 
    count(*),
    (select count(*) from test1 where test1.id = main.id) as test1_count,
    (select count(*) from test2 where test2.id = main.id) as test2_count
from main

答案 1 :(得分:1)

您创建了包含以下内容的表:

表格主要

id
----
1

表格测试1

id
----
1
1

表格测试2

id
----
1
1
1

当您加入此项时,您将获得以下

id  id  id 
-----------
1   1   1
1   1   1
1   1   1
1   1   1
1   1   1
1   1   1

那么SQL应该如何回答不同?

您可以致电:

SELECT id,COUNT(id) FROM main GROUP BY id

对于每个表,然后通过id加入它们。

答案 2 :(得分:0)

不确定这是否与MySQL完全一样(我正在使用Oracle):

  1  select main.id, t1.rowcount, t2.rowcount
  2  from main
  3    left join (select id,count(*) rowcount from test1 group by id) t1
  4              on t1.id = main.id
  5    left join (select id,count(*) rowcount from test2 group by id) t2
  6*             on t2.id = main.id

SQL> /

    ID   ROWCOUNT   ROWCOUNT

     1          2          3

答案 3 :(得分:0)

您无意中在test1和test2之间创建了笛卡尔积,因此test1中的每个匹配行都与test2中的每个匹配行组合在一起。因此,两个计数的结果是test1 中匹配行的计数乘以 test2中匹配行的计数。

这是一个常见的SQL反模式。很多人都有这个问题,因为他们认为他们必须在一个查询中得到两个计数。

此线程中的其他人已经建议通过创造性地使用子查询来补偿笛卡尔积,但解决方案只是运行两个单独的查询:

select main.id, count(test1.id)
from main
left join test1 on main.id=test1.id
group by main.id;

select main.id, count(test2.id) 
from main
left join test2 on main.id=test2.id
group by main.id;

您不必在单个SQL查询中执行每项任务!通常,代码更容易 - 并且RDBMS更容易执行 - 多个简单的查询。

答案 4 :(得分:0)

您可以使用以下方法获得所需的结果:

SELECT COUNT(*) as main_count, 
(SELECT COUNT(*) FROM table1) as table1Count,
(SELECT COUNT(*) from table2) as table2Count FROM main
相关问题