2017-07-18 56 views
-1

任何人都可以請幫助我下面的查詢,其中我使用IN子句導致性能問題。我想爲它使用JOIN,但不知道如何做這樣的查詢。mysql如何使用JOIN而不是IN與WHERE子句

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)"; 
+0

請問[手冊](https://dev.mysql.com/doc/refman/5.7/en/join.html)中的例子沒有幫助嗎? –

+0

你有嘗試過自己嗎?你面臨的挑戰是什麼? – money

+0

@money是的,我試過,但在這裏我主要關心的不是獲得查詢我也想知道如何選擇子句的具體要求,什麼是獲得更快的響應形式查詢的最佳選擇。 – user2423768

回答

1

我重寫使用連接查詢:

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 
+0

感謝Dave進行查詢,但它給出了一個錯誤「Column'last_updated_timestamp'where where clause is ambiguous」。 – user2423768

+0

你好,我已經更新了我的答案。 – Dave94

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 s。在大多數情況下,閱讀和優化會更容易。
+0

謝謝戈登,解釋。我必須創建更復雜的查詢這個知識幫助我:) – user2423768