[英]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.