mysql—表中两列的计数,以及一列与另一列的计数

mysql—表中两列的计数,以及一列与另一列的计数,mysql,sql,join,count,Mysql,Sql,Join,Count,我希望将这些查询纳入其中: 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.fir

我希望将这些查询纳入其中:

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;
但它为表2返回了错误的值。
如何解决此问题?

一种简单的方法是使用子查询:

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中工作。在其他数据库中,第三列需要一个聚合函数。

您能给出示例数据、输出和所需输出吗?我已经从表1和表2中了解了。我想计算用户关注度,关注度和帖子数量。数据如下:user_id:1,follows:11,follows:null-user_id:1,follows:24,follows:null-user_id:1,follows:null,follows:54和posts表中的post_id:22,user_id:1-post_id:26,user_id:1。当我添加group by table2.post_id时,它返回表1的正确值,但不返回表2的正确值。下面和后面是目标用户的id,而不是此处的计数。