Oracle DISTINCT忽略导致性能问题的主键索引

时间:2015-01-07 02:54:51

标签: sql oracle

当我在下面的查询中包含distinct时,在GROUP_WIDGET表上发生了全表扫描,下面的查询非常慢。当我删除不同时它很快。任何想法为什么性能在使用distinct时会受到影响?

Tables:
COMPONENT
ID (primary key)

GROUP
ID (primary key)

WIDGET
ID (primary key)
COMPONENT_ID (foreign key to COMPONENT TABLE)

GROUP_WIDGET (join table between GROUP AND WIDGET)
ID (primary key)
GROUP_ID (foreign key to GROUP table)
WIDGET_ID (foreign key to WIDGET table)
***all foreign keys are indexed

非常慢(30秒):

SELECT DISTINCT GROUP_WIDGET.ID FROM GROUP_WIDGET GW, WIDGET W WHERE W.COMPONENT_ID=12345 AND W.ID=GW.WIDGET_ID

非常快(1秒):

SELECT GROUP_WIDGET.ID FROM GROUP_WIDGET GW, WIDGET W WHERE  W.COMPONENT_ID=12345 AND W.ID=GW.WIDGET_ID

1 个答案:

答案 0 :(得分:1)

而不是:

SELECT GW.ID
  FROM GROUP_WIDGET GW, WIDGET W
 WHERE W.COMPONENT_ID=12345 AND W.ID=GW.WIDGET_ID

我想您可以尝试使用WHERE EXISTS

SELECT gw.id
  FROM group_widget gw
 WHERE EXISTS ( SELECT 1 FROM widget w
                 WHERE w.id = gw.widget_id
                   AND w.component_id = 12345 )

这样您根本不必使用DISTINCT