简体   繁体   English

MYSQL AND或多对多表

[英]MYSQL AND OR On Many To Many Table

Kind of a convoluted question but, basically I have a many to many table word_relationships : 有点复杂的问题,但基本上我有很多表word_relationships

+-----+--------+--------+
|  ID | WORD_A | WORD_B |
+-----+--------+--------+
|  1  |  784   |  893   |
+-----+--------+--------+
|  2  |  930   |  839   |
+-----+--------+--------+
|  3  |  093   |  647   |
+-----+--------+--------+

it is a list of word a and word b relationships. 它是word aword b关系的列表。 I need to query to find if the relationship between word_a and word_b exists. 我需要查询以查找word_a和word_b之间的关系是否存在。 What would be the proper syntax for this if the words can be either word A OR word b? 如果单词可以是单词A或单词b,那么正确的语法是什么?

In my head it's 在我的脑海里

w1 = 784
w2 = 893
"SELECT ID FROM word_relationships WHERE WORD_A = w1 OR WORD_B = w1 AND WORD_A = w2 OR WORD_B = w2";

This doesn't seem to work because I get back a result for any match. 这似乎不起作用,因为我得到了任何比赛的结果。 Anyone familiar with this situation and know the proper syntax? 熟悉这种情况并知道正确的语法的人吗?

Thanks in advance. 提前致谢。

I think you can just put parenthesis in your where clauses to combine the ORs properly. 我认为您可以将括号放在where子句中以正确组合OR。

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. 顺便说一句,您返回所有结果的原因是因为SQL运算符的优先级顺序。

Since AND is evaluated before OR, it meant that by default the clause was grouped as follows: 由于AND是在OR之前求值的,因此默认情况下该子句的分组方式如下:

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. 这将带来比您期望的更多的回报。

This should work: 这应该工作:

SELECT 
  id 
FROM 
  word_relationships
WHERE 
 (Word_A = w1 AND Word_B = w2)
OR 
 (Word_A = w2 AND Word_B = w1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM