Where 'foo' OR 'bar' AND 'lol' OR 'rofl' MySQL

折月煮酒 提交于 2019-12-23 12:51:01

问题


In what order would this be evaluated. My intension is that if it finds either foo or bar, it would also search for lol and rofl.
Is this totally in the woods? And if so, how would one evaluate an expression like that.


回答1:


The AND operator has higher precedence than OR in MySql, so your current expression evaluates as:

WHERE 'foo' OR ('bar' AND 'lol') OR 'rofl'

Add parentheses to the expression if you want to force the evaluation order:

WHERE ('foo' OR 'bar') AND ('lol' OR 'rofl')



回答2:


AND will be processed first, after that OR will be processed. So, it will be:

'foo' OR ('bar' AND 'lol') OR 'rofl'

After that, it is left to right order.




回答3:


take a look at the documentation - AND has a higher precedence, so it would be like this:

WHERE 'foo' OR ( 'bar' AND 'lol' ) OR 'rofl'



回答4:


SELECT
  Id, Name
FROM
  TestTable
WHERE
    (Name = 'foo') OR (Name = 'bar') AND (Name = 'lol') OR (Name = 'rofl')

Will give you the following result in MS SQL Server:

1 foo
4 rofl

So it seems it will combine bar AND lol and evals foo and rofl seperately like this:

SELECT
      Id, Name
    FROM
      TestTable
    WHERE
        (Name = 'foo') OR ((Name = 'bar') AND (Name = 'lol')) OR (Name = 'rofl')

What you probably want to do is (technically):

SELECT
      Id, Name
    FROM
      TestTable
    WHERE
        ((Name = 'foo') OR (Name = 'bar')) AND ((Name = 'lol') OR (Name = 'rofl'))


来源:https://stackoverflow.com/questions/4266346/where-foo-or-bar-and-lol-or-rofl-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!