有没有一种方法可以选择带有一个查询的两个表的COUNT?使用MYSQL在一个查询中选择两个表中的COUNT
目前我有以下,它不能正常工作。
SELECT
COUNT(t1.id) as t1_amount,
COUNT(t2.id) as t2_amount
FROM
table1 t1,
table2 t2
有没有一种方法可以选择带有一个查询的两个表的COUNT?使用MYSQL在一个查询中选择两个表中的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
。这是两张桌子之间的笛卡尔产品。
感谢戈登哪种方法更有效? – Bruce
@ bluebill1049。 。 。在效率方面它们应该是一样的。就个人而言,我更喜欢第二种方法,因为我倾向于避免在select语句中选择select。 –
谢谢戈登,我会按照你的建议 – Bruce