gpt4 book ai didi

MySQL select count count different data from same tables 最佳方法

转载 作者:搜寻专家 更新时间:2023-10-30 20:08:25 24 4
gpt4 key购买 nike

我正在尝试获取同一个表中不同 where 子句中的值的计数。哪个是最好的方法

SELECT * FROM 
(SELECT COUNT(id) FROM table WHERE post_id = 123 AND action_type IN(1,3,7,9,10)) as 'a',
(SELECT COUNT(id) FROM table WHERE post_id = 123 AND action_type IN(2,7,8,18)) as 'b'

SELECT COUNT(id) FROM table WHERE post_id = 123 AND action_type IN(1,3,7,9,10)
SELECT COUNT(id) FROM table WHERE post_id = 123 AND action_type IN(2,7,8,18)

注意:表格包含数百万个值

最佳答案

您可以使用条件聚合,以便在没有子查询的情况下在一个查询中获取数据:

SELECT COUNT(CASE WHEN action_type IN(1,3,7,9,10) THEN id END) AS count_1,
COUNT(CASE WHEN action_type IN(2,7,8,18) THEN id END) AS count_2
FROM table
WHERE id = 123

关于MySQL select count count different data from same tables 最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40101905/

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