【发布时间】:2018-09-04 17:29:36
【问题描述】:
我有这个查询,它生成大约 40,000 条记录,这个查询的执行时间大约是 1 分 30 秒。
SELECT DISTINCT
a.ID,
a.NAME,
a.DIV,
a.UID,
(select NAME from EMPLOYEE where UID= a.UID and UID<>'') as boss_id,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 1 and id = a.ID) as TERM1,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 2 and id = a.ID) as TERM2,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 3 and id = a.ID) as TERM3,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 4 and id = a.ID) as TERM4,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 5 and id = a.ID) as TERM5,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 6 and id = a.ID) as TERM6,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 7 and id = a.ID) as TERM7,
(select DATE(MAX(create_time)) from XYZ where XYZ_ID= 8 and id = a.ID) as TERM8
FROM EMPLOYEE a
WHERE ID LIKE 'D%'
我尝试使用 group by、不同类型的连接来缩短执行时间,但未能成功。ABC 和 XYZ 表都已编入索引。
另外,我认为这个问题的根本原因是DISTINCT 关键字或MAX 函数。
如何优化上述查询以将执行时间缩短到至少不到一分钟?
感谢任何帮助。
【问题讨论】:
-
改为使用 GROUP BY。将子查询转换为 LEFT JOIN。使用 case 表达式进行条件聚合。
-
索引是什么?字段类型有哪些?什么数据库?
-
请在您的帖子中添加表定义以及任何键或索引。另外,请告诉我们这是哪个 DBMS 产品,因为不同供应商的调优差异很大。
-
您使用的是哪个DBMS? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加标签
postgresql、oracle、sql-server、db2、...