2011-09-21 45 views
11

我做了我自己的論壇。在進行搜索時,我想找到兩個(或更多)特定用戶參與的任何線程。我想出了這個:MySQL in-operator必須匹配所有值嗎?

SELECT * FROM table1 INNER JOIN table2 
ON table1.threadid=table2.threadid 
WHERE table2.threadcontributor IN ('1','52512') 

之前意識到這實際上意味着'1' OR '52512'

有沒有辦法讓它工作,以便所有的id都匹配?

+0

請給你實際的表結構,包括PK。 –

+0

請發佈您的真實代碼或至少是table1和table2。我的第一個aproach讓我加入兩倍的線程表。請閱讀這篇文章和anwser http://stackoverflow.com/questions/7492699/how-can-i-structure-a-query-to-give-me-only-the-rows-that-match-all-values- in-ac/7493309#7493309 –

回答

20
SELECT * 
    FROM table1 
     INNER JOIN table2 
      ON table1.threadid=table2.threadid 
    WHERE table2.threadcontributor IN ('1','52512') 
    GROUP BY table1.PrimaryKey 
    HAVING COUNT(DISTINCT table2.threadcontributor) = 2 
+0

兩個(或更多)特定用戶,所以它應該是'> = 2' –

+3

@ViswanathanIyer但是'IN'子句中只指定了2個值。如果目標是確保您匹配'IN'子句中列出的所有值,那麼'HAVING'中測試的值應該與爲'IN'指定的值的數量匹配。 –

+0

@Joe - ViswanathanIyer不是OP。 –

相關問題