[英]Select COUNT in two table in one query with 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
。 這將在兩個表之間進行笛卡爾乘積運算。
由於它們是兩個單獨的查詢,並且您希望它們在同一結果集中,因此請使用UNION:
(SELECT COUNT(*) AS `table1_total` FROM `table1`)
UNION
(SELECT COUNT(*) AS `table2_total` FROM `table2`);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.