简体   繁体   English

Mysql语句中的逻辑表达式未提供期望的结果

[英]Logical expression in Mysql statement not giving desired result

Okey, first of all, let me draw the related table and dummy data that being used before going further( simple table structure to re-produce the issue ): 首先,Okey,让我画出相关的表和伪数据,然后再继续使用( 简单的表结构来重现问题 ):

|----------------------------------------------|
|users                                         |
|----------------------------------------------|
|ID | name            | email                  | 
|----------------------------------------------| 
|1  | jack jill       | jackjill@gmail.com     |
|----------------------------------------------|                  
|2  | jack jacky      | jackjacky@gmail.com    |
|----------------------------------------------|

And here is mysql query statement being used : 这是正在使用的mysql查询语句:

SELECT *
FROM `users`
WHERE `ID` = 1
AND  `name` LIKE '%jacky%'
OR  `email` LIKE '%jacky%'

Expected result : Row no 1 预期结果:第1行

Actual result : Row no 2 实际结果:第2行

Question : 题 :

1) Is the logical expression in above statement do the short circuit evaluation? 1)上述陈述中的逻辑表示是否进行短路评估?

2) If yes( from question no 1 ), why it not return the 1st row as the first expression already evaluated to TRUE. 2)如果是(来自问题1),为什么它不返回第一行,因为第一个表达式已经计算为TRUE。

3) If not( from question no 1 ), which expression its evaluated and at what order the operator precedence occurred? 3)如果不是(从问题1开始),则评估哪个表达式,并且运算符优先级按什么顺序发生?

All these are playing in my mind right now, and i'm really confuses on how it evaluated. 所有这些现在都在我脑海中浮现,我真的对其评估方式感到困惑。 Even it just a simple SQL statement. 即使只是一个简单的SQL语句。 Really appreciated if someone can explain deep down about this. 如果有人可以对此进行深入的解释,我将不胜感激。

In SQL, the AND operator has precedence over OR . 在SQL中, AND运算符的优先级高于OR So you probably want to override that with parentheses like this: 因此,您可能希望使用如下括号将其覆盖:

SELECT *
FROM `users`
WHERE `ID` = 1
AND  (   `name` LIKE '%jacky%'
     OR  `email` LIKE '%jacky%'
     )

In your version the last condition (ie email LIKE '%jacky%' ) was enough to get a match. 在您的版本中,最后一个条件(即email LIKE '%jacky%' )足以匹配。 You could imagine the default precedence like this: 您可以想象这样的默认优先级:

SELECT *
FROM `users`
WHERE (     `ID` = 1
       AND  `name` LIKE '%jacky%'
      )
OR    `email` LIKE '%jacky%'

With the corrected version there will in fact be no more match, as there is no jacky in the name field of the first row, nor in its email field. 使用更正后的版本实际上将不再匹配,因为第一行的名称字段及其电子邮件字段中没有jacky

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

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