次のクエリがあるとします。
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 つのクエリを記述する代わりに、これらすべての詳細を 1 つのクエリで取得できる方法はありますか?
グループ化?
SELECT count(*) AS count, info FROM info WHERE uid=1 GROUP BY info
count | info
5 a
10 b
11 c
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