[英]mysql - count of two columns of a table and one column from another
我希望這個查詢能合而為一:
select count(first_column) as first from table1 where user_id = $id
select count(second_column) as second from table1 where user_id = $id
select count(first_column) as third from table2 where user_id = $id
我有這個:
select COUNT(table1.first_column) AS first,
COUNT(table1.second_column) AS second,
COUNT(table2.first_column) AS third
from table2 inner join
table2 on table1.user_id = table2.user_id
where table1.user_id = 1;
但它為table2返回錯誤的值。 我怎樣才能解決這個問題?
一種簡單的方法是使用子查詢:
select (select count(first_column) as first from table1 where user_id = $id) as first,
(select count(second_column) as second from table1 where user_id = $id) as second,
(sselect count(first_column) as third from table2 where user_id = $id) as third;
因為前兩個來自同一張表,所以您可以考慮:
select count(t1.first_column), count(t1.second_column), t2.third_column
from table1 t1 cross join
(select count(third_column as third from table2) t2
where t1.user_id = $id;
這將在MySQL中工作。 在其他數據庫中,第三列需要一個聚合函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.