假設我有以下查詢。將3個查詢優化爲單個查詢的最佳方式
SELECT count(*) FROM info WHERE info = 'a' and uid = 1
SELECT count(*) FROM info WHERE info = 'b' and uid = 1
SELECT count(*) FROM info WHERE info = 'c' and uid = 1;
而不是編寫3個查詢有什麼辦法讓我可以在一個查詢中獲得所有這些細節?
假設我有以下查詢。將3個查詢優化爲單個查詢的最佳方式
SELECT count(*) FROM info WHERE info = 'a' and uid = 1
SELECT count(*) FROM info WHERE info = 'b' and uid = 1
SELECT count(*) FROM info WHERE info = 'c' and uid = 1;
而不是編寫3個查詢有什麼辦法讓我可以在一個查詢中獲得所有這些細節?
SELECT info, count(*) as info_cnt
FROM T
WHERE uid = 1 and info IN ('a', 'b','c')
GROUP BY info
SELECT info,
SUM(CASE WHEN info = 'a' THEN 1 ELSE 0 END) `a`,
SUM(CASE WHEN info = 'b' THEN 1 ELSE 0 END) `b`,
SUM(CASE WHEN info = 'c' THEN 1 ELSE 0 END) `c`
FROM tableName
WHERE uid = 1 AND info IN ('a','b','c')
GROUP BY info
這會給你造成排
uid a b c
==============
1 5 2 6
感謝這項工作 – shanks
這可以簡化更多,'WHERE uid = 1和信息IN('a','b' , 'C')' –