i am trying to get count of values in same table but different where clause. Which one is best approach for that
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)
Note: Table contains millions of values
You can use conditional aggregation so as to get data in one query without subqueries:
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
第一个,因为它将只执行一次并且优化了方式
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.