gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:51:18 26 4
gpt4 key购买 nike

如何优化此 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

最佳答案

当你想在 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)

关于mysql - 如何使用同一张表中的多个 SELECT 优化 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16423292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com