mysql如何使用JOIN而不是IN与WHERE子句

时间:2017-07-18 12:31:56

标签: mysql

任何人都可以帮我解决下面的查询,其中我使用了导致性能问题的IN子句。我想使用JOIN但不确定如何进行此类查询。

select * 
from user_followings 
where followed_id = 'xyz' AND owner_id IN (
   select DISTINCT owner_id 
   from feed_events 
   where DTYPE = 'PLAYLIST' AND last_updated_timestamp > '20-04-2017' AND (feed_type = 'PLAYED_PLAYLIST' OR feed_type = 'STARTED_LISTENING') 
   order by last_updated_timestamp DESC)";   

2 个答案:

答案 0 :(得分:1)

我使用join重写了您的查询:

 SELECT *
    FROM user_followings
    INNER JOIN feed_events ON user_followings.owner_id = feed_events.owner_id
    WHERE followed_id = 'xyz'
        AND DTYPE = 'PLAYLIST'
        AND feed_events.last_updated_timestamp > '20-04-2017'
        AND (
            feed_type = 'PLAYED_PLAYLIST'
            OR feed_type = 'STARTED_LISTENING'
            )
    ORDER BY last_updated_timestamp DESC

答案 1 :(得分:1)

join可能不是最佳方法。使用exists

select uf.* 
from user_followings uf
where uf.followed_id = 'xyz' and
      exists (select 1
              from feed_events fe
              where uf.owner_id = fe.owner_id and
                    fe.DTYPE = 'PLAYLIST' and
                    fe.last_updated_timestamp > '2017-04-20' and
                    fe.feed_type in ('PLAYED_PLAYLIST', 'STARTED_LISTENING') 
             );

您需要feed_events(owner_id, dtype, last_updated_timestamp, feed_type)user_followings(followed_id, owner_id)上的索引。

其他说明:

  • ORDER BY在这样的子查询中没用。
  • 使用标准日期格式(YYYY-MM-DD)作为常数日期。
  • 使用IN代替一堆OR。在大多数情况下,它更容易阅读和优化。