MySQL选择从同一个表中计算不同的数据最佳方法

时间:2016-10-18 07:18:12

标签: mysql database

我试图在同一个表中获取值,但是不同的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'

OR

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)

注意:表包含数百万个值

2 个答案:

答案 0 :(得分:4)

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

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 

答案 1 :(得分:0)

第一,因为它只会执行一次优化方式