将3个查询优化为单个查询的最佳方法

时间:2013-01-21 12:38:48

标签: mysql sql select

假设我有以下疑问。

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 个答案:

答案 0 :(得分:4)

分组?

SELECT count(*) AS count, info FROM info WHERE uid=1 GROUP BY info

count | info
5       a
10      b
11      c

答案 1 :(得分:4)

SELECT info, count(*) as info_cnt 
FROM T
WHERE uid = 1 and info IN ('a', 'b','c')
GROUP BY info

答案 2 :(得分:2)

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