【问题标题】:mysql - count of two columns of a table and one column from anothermysql - 一个表的两列和另一列的计数
【发布时间】:2018-03-08 14:43:10
【问题描述】:

我希望这些查询合二为一:

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

【问题讨论】:

  • 你能给出示例数据、你的输出和想要的输出吗?
  • 我关注并关注了 table1 和 table2 的帖子。我想计算用户关注、关注和帖子数。数据是这样的:user_id:1,follows:11,followed:null - user_id:1,follows:24,followed:null - user_id:1,follows:null,followed:54和posts表post_id:22,user_id :1 - post_id:26, user_id:1。当我通过 table2.post_id 添加组时,它返回正确的 table1 但不是 table2。 follow和followed是目标user_id的id,不是这里的count。

标签: mysql sql join count


【解决方案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 中工作。在其他数据库中,您将需要第三列的聚合函数。

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2021-09-04
    • 2023-03-19
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多