MYSQL AND OR On Many To Many Table

后端 未结 2 741
暗喜
暗喜 2021-01-26 21:11

Kind of a convoluted question but, basically I have a many to many table word_relationships:

+-----+--------+--------+
|  ID | WORD_A | WORD_B |
+--         


        
相关标签:
2条回答
  • 2021-01-26 21:46

    I think you can just put parenthesis in your where clauses to combine the ORs properly.

    SELECT ID 
    FROM word_relationships 
    WHERE (WORD_A = w1 OR WORD_B = w1) 
    AND (WORD_A = w2 OR WORD_B = w2)
    

    I'm not totally sure I'm understanding your intention for the query though. Hope that helps.

    BTW, the reason you were getting back all of the results is because of the order of precedence for SQL operators.

    Since AND is evaluated before OR, it meant that by default the clause was grouped as follows:

    WHERE WORD_A = w1 
    OR (WORD_B = w1 AND WORD_A = w2) 
    OR WORD_B = w2
    

    which would return many more than you were expecting.

    0 讨论(0)
  • 2021-01-26 21:57

    This should work:

    SELECT 
      id 
    FROM 
      word_relationships
    WHERE 
     (Word_A = w1 AND Word_B = w2)
    OR 
     (Word_A = w2 AND Word_B = w1)
    
    0 讨论(0)
提交回复
热议问题