使用MYSQL在一个查询中的两个表中选择COUNT

时间:2013-04-18 01:11:08

标签: mysql sql

有没有办法可以选择带有两个表和一个查询的COUNT。

目前,我有以下内容,但无效。

SELECT 
COUNT(t1.id) as t1_amount,
COUNT(t2.id) as t2_amount
FROM
table1 t1,
table2 t2

2 个答案:

答案 0 :(得分:6)

这是一种方式:

select (select count(*) from table1) as t1_amount,
       (select count(*) from table2) as t2_amount

这是另一种方式:

select t1.t1_amount, t2.t2_amount
from (select count(*) as t1_amount from table1) t1 cross join
     (select count(*) as t2_amount from table2) t2

您的方法不起作用,因为,子句中的from执行cross join。这是两个表之间的笛卡尔积。

答案 1 :(得分:1)

由于它们是两个单独的查询,并且您希望它们位于同一结果集中,因此请使用UNION:

(SELECT COUNT(*) AS `table1_total` FROM `table1`)
  UNION
(SELECT COUNT(*) AS `table2_total` FROM `table2`);