重写查询以避免带有子查询的WHERE IN

时间:2014-03-18 15:39:23

标签: mysql sql subquery where-in

我有以下查询返回正确的结果,但我知道与WHERE IN子句中的子查询相关的开销。

SELECT event_start_date 
  FROM events
       JOIN joins 
            ON event_id = join_event_id
       JOIN groups 
            ON join_type_id IN (SELECT group_id 
                                  FROM view_groups 
                                 WHERE user_id = 3)
 WHERE user_id = 3
       AND event_start_date >= now()
GROUP BY 
       event_start_date;

任何人都可以帮忙重写此查询以避免子查询和/或WHERE IN子句。

3 个答案:

答案 0 :(得分:1)

试试这个:

 SELECT event_start_date FROM events
 JOIN joins ON event_id = join_event_id
 join view_groups on ............condition here
 JOIN groups ON join_type_id = view_groups.group_id 
 WHERE user_id = 3
 AND event_start_date >= now()
 GROUP BY event_start_date;

答案 1 :(得分:0)

试试这个...

另外,为什么在Select中使用Group by而没有聚合函数?

SELECT event_start_date
FROM events
INNER JOIN joins
    ON event_id = join_event_id
WHERE user_id = 3
    AND event_start_date >= now()
    AND EXISTS (
        SELECT group_id
        FROM view_groups
        WHERE user_id = 3
            AND group_id = join_type_id
        )
GROUP BY event_start_date;

答案 2 :(得分:0)

MySQL会optimize uncorrelated subqueries(你的例子中有):

  

MySQL只执行一次不相关的子查询。使用EXPLAIN来制作   确定给定的子查询确实是不相关的。

如果您的子查询只返回一个结果,请务必使用相等的结果:

  

对于始终返回一行的不相关子查询,IN始终为   慢于=。

无论如何,这是您将查询重写为JOIN的方式:

SELECT events.event_start_date 
  FROM events
       JOIN joins 
            ON events.event_id = joins.join_event_id
       JOIN view_groups
            ON view_groups.user_id = 3
       JOIN groups 
            ON groups.join_type_id = view_groups.group_id
 WHERE events.user_id = 3
       AND events.event_start_date >= NOW()
 GROUP BY 
       events.event_start_date;