📜  MySQL |运算符优先级

📅  最后修改于: 2022-05-13 01:55:49.615000             🧑  作者: Mango

MySQL |运算符优先级

运算符优先级指定当两个或多个具有不同优先级的运算符在表达式中相邻时计算运算符符的顺序。

例如,与 (1+2)/3 相比,1+2/3 给出不同的结果。就像所有其他编程语言 C、C++、 Java等一样。MySQL 也有优先规则。

下表描述了 MySQL 中的运算符优先级,从最高到最低。同一组中的运算符具有相同的优先级。

OperatorDescription
INTERVALReturn the index of the argument that is less than the first argument
BINARY
COLLATE
This is a type that stores binary byte strings
This clause override whatever the default collation is for comparison
!Negate values

~
It change the sign of the operand
It inverts the bits of operand
^Bitwise XOR
*
/
DIV
%, MOD
Multiplication operator
Division operator
Integer Division (discard the fractional part of division)
Modulo operator

+
Minus operator
Addition operator
<<
>>
Shift a (BIGINT) number or binary string to left
Shift a (BIGINT) number or binary string to right
&Bitwise AND
|Bitwise OR
=
<=>
>=, >
<=, <
<>, !=
IS
LIKE
REGEXP
IN
Comparison operator
NULL-safe equal to operator
Greater than/Greater than or equal to
Less than/Less than or equal to
Not Equal to operator
Test a value against a boolean value
Pattern matching operator
Matches the string expression with the regular expression
Check whether a value is present in list or not
BETWEEN
CASE WHEN THEN ELSE
Check whether a value is within a range of values
Case operator
NOTNegates Value
AND, &&Logical AND
XORLogical XOR
OR, ||Logical OR
=
:=
Assign a value (as part of a SET statement/SET clause in an UPDATE statement)
Assign a value

这些运算符优先级规则极大地影响了我们的 MySQL 查询。如果不知道运算符优先级,我们可能会得到意想不到的结果。要理解这一点,请考虑下表Student

idnamemarks
1Payal12
2Utkarsh9
3Reeta19
4Sunny15
5Shanu5
6Punit7

从上表中,我们想要那些分数大于 10 且姓名以“p”或“s”开头的学生的结果。所以,它的查询可以写成——

mysql>select * 
from student 
where marks>10 and name like 'p%' 
                   or name like 's%'; 

结果:
它将产生所需的结果:

idnamemarks
1Payal12
4Sunny15
6Punit7

此结果集与查询中的预期不符。因为它给出了分数低于 10 的学生“Punit”的结果,这不是必需的。由于与 OR 相比,运算符AND 的优先级更高,因此上述查询给出了所有分数大于 10 且姓名以 's' 开头的学生的结果,以及那些姓名以 'p' 开头的学生的结果也在输出中给出。所以,括号的作用就来了。上述查询可以写成,

mysql>select * 
from student 
where marks>10 and (name like 'p%' 
                       or name like 's%');

结果:
它将产生所需的结果:

idnamemarks
1Payal12
4Sunny15


因此,可以通过使用括号来覆盖运算符的这种优先级。