假设我有以下查询。
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 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