gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:21:31 24 4
gpt4 key购买 nike

我希望这个查询进入一个:

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

关于mysql - 表的两列和另一表的一列的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49175820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com