有没有办法我可以通过一个查询选择两个表的 COUNT。
目前我有以下内容,但无法正常工作。
SELECT
COUNT(t1.id) as t1_amount,
COUNT(t2.id) as t2_amount
FROM
table1 t1,
table2 t2
这是一种方法:
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
由于它们是两个独立的查询,并且您希望它们在同一个结果集中,请使用 UNION:
(SELECT COUNT(*) AS `table1_total` FROM `table1`)
UNION
(SELECT COUNT(*) AS `table2_total` FROM `table2`);