如何使用同一个表中的多个SELECT优化SQL查询?

时间:2013-05-07 15:46:35

标签: mysql sql query-optimization

如何优化SQL查询?

(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '0') AS a,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '1') AS b,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '2') AS c

2 个答案:

答案 0 :(得分:7)

当您想在MySQL中执行数据透视时,您可以对Case语句进行聚合

SELECT 
    SUM ( CASE WHEN other_same_field  = 0 THEN same_field ELSE 0 END) as A,
    SUM ( CASE WHEN other_same_field  = 1 THEN same_field ELSE 0 END) as B,
    SUM ( CASE WHEN other_same_field  = 2 THEN same_field ELSE 0 END) as C
FROM same_table
WHERE other_same_field IN (0, 1, 2)

答案 1 :(得分:4)

这将为您提供垂直结果。

SELECT other_same_field, SUM(same_field)
FROM same_table
WHERE other_same_field IN (0, 1, 2)
GROUP BY other_same_field