mysql - 表的两列和另一列的一列

时间:2018-03-08 14:43:11

标签: 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.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的错误值。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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

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