SQL查询需要太多时间来执行

时间:2014-07-17 12:25:23

标签: sql

我的查询有问题需要花费太多时间才能执行。查询是:

SELECT id, name 
  FROM user 
 WHERE id IN ( SELECT DISTINCT ( user_id ) 
                 FROM `webchat` 
                WHERE closed = 0 )

webchat.closed user.id 是索引。查询需要6秒钟才能完成。

但是如果我这样做的话:

SELECT DISTINCT ( user_id ) 
  FROM `webchat` 
 WHERE closed = 0

完成只需0.00002秒。它返回两个结果,16023和14020.如果我执行此查询:

SELECT id, name FROM user WHERE id IN (16023, 14020) 

只需0.00004秒即可完成。

那么,为什么第一个查询需要6秒才能完成?

3 个答案:

答案 0 :(得分:3)

尝试这种方式:

SELECT DISTINCT user.id, user.name 
  FROM user INNER JOIN `webchat` on user.id = `webchat`.user_id
 WHERE `webchat`.closed = 0 

答案 1 :(得分:1)

这是您的查询:

SELECT u.id, u.name
FROM user u
WHERE u.id IN ( SELECT DISTINCT ( user_id ) FROM webchat WHERE closed = 0 )

首先,distinct在子查询中是多余的。其次,许多数据库比exists处理in更好。试试这个:

SELECT u.id, u.name
FROM user u
WHERE EXISTS (select 1 from webchat wc where wc.closed = 0 and wc.user_id = u.id);

索引将有助于此查询。尝试复合索引webchat(user_id, closed)

答案 2 :(得分:1)

试试这个:

SELECT id, name 
FROM user 
INNER JOIN `webchat` on `webchat`.user_id = user.id and `webchat`.closed = 0