MySQL MySQL查询AND OR运算符逻辑

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11067451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:51:00  来源:igfitidea点击:

MySQL query AND OR operator Logic

mysqldatabasecomputer-science

提问by ronnockoch

I'm in the middle of a project for my Comp Science project for monday, and i came across a MySQL question regarding a Query.

我正在为我的 Comp Science 项目做一个周一的项目,我遇到了一个关于查询的 MySQL 问题。

What I want to achieve, through words is this.

我想通过文字实现的就是这个。

If the column to=jake and column from=connorOR column to=connor and column from=jakeget the cID from that specific table.

如果列to=jake 和列 from=connorOR列 to=connor 和列 from=jake从该特定表中获取 cID。

What I have so far is this

到目前为止我所拥有的是这个

 $query="SELECT cID FROM conversation WHERE to='$to' AND to='$from' OR to='$from' AND        from='$to'";

What is there that I can do to get this query to work? Thanks in advance!

我可以做些什么来使此查询正常工作?提前致谢!

回答by Michael Berkowski

You just need a couple pairs of ()to group the two conditional pairs, separated by a logical OR

您只需要几对()来将两个条件对分组,并由逻辑分隔OR

$query="
  SELECT cID 
  FROM conversation
  WHERE 
      /* to Jake, from Connor */
     (`to`='$to' AND `from`='$from')
      /* OR to connor, from jake */ 
     OR  (`to`='$from' AND `from`='$to')";

Note: FROMand TOare both MySQL reserved keyword, and thus require quoting with backticks.

注意:FROMandTO都是MySQL 保留关键字,因此需要用反引号引用。

回答by Stefan

This is untested but I would think you need to put the to='$to' AND to='$from' (which should be from not to i guess??) into brackets??

这是未经测试的,但我认为您需要将 to='$to' AND to='$from' (应该是 from not to 我猜??)放入括号中??

Just realised someone else put this as i was typing it

刚刚意识到有人在我打字的时候把这个放了

回答by Tschallacka

$query="SELECT cID FROM conversation WHERE 
(to='$to' OR to='$from' OR to='$from') AND from='$to'";