表 14.4 比较运算符Table 14.4 Comparison Operators
| 名称Name | 说明Description |
|---|---|
>> |
大于运算符Greater than operator |
>=>= |
大于或等于运算符Greater than or equal operator |
<< |
小于运算符Less than operator |
<>, !=<>, != |
不等于运算符Not equal operator |
<= |
小于或等于运算符Less than or equal operator |
<=> |
NULL 安全等于运算符NULL-safe equal to operator |
= |
等于运算符Equal operator |
BETWEEN ... AND ... |
一个值是否在某一数值范围内Whether a value is within a range of values |
COALESCE() |
返回第一个非空参数Return the first non-NULL argument |
EXISTS() |
查询结果是否包含任何行Whether the result of a query contains any rows |
GREATEST() |
返回最大的参数Return the largest argument |
IN() |
一个值是否在一组值中Whether a value is within a set of values |
INTERVAL() |
返回小于第一个参数的参数索引Return the index of the argument that is less than the first argument |
IS |
将值与布尔值进行测试Test a value against a boolean |
IS NOTIS NOT |
将值与布尔值进行测试Test a value against a boolean |
IS NOT NULLIS NOT NULL |
非空值测试NOT NULL value test |
IS NULLIS NULL |
NULL 值测试NULL value test |
ISNULL() |
测试参数是否为 NULLTest whether the argument is NULL |
LEAST() |
返回最小的参数Return the smallest argument |
LIKE |
简单的模式匹配Simple pattern matching |
NOT BETWEEN ... AND ...NOT BETWEEN ... AND ... |
某个值是否不在某个值的范围内Whether a value is not within a range of values |
NOT EXISTS() |
查询结果是否不包含任何行Whether the result of a query contains no rows |
NOT IN() |
某个值是否不在一组值中Whether a value is not within a set of values |
NOT LIKE |
简单模式匹配的取反Negation of simple pattern matching |
STRCMP() |
比较两个字符串Compare two strings |
比较操作的结果是 1(TRUE)、0(FALSE)或 NULL。这些操作适用于数字和字符串。字符串会在必要时自动转换为数字,数字也会自动转换为字符串。Comparison operations result in a value of 1
(TRUE), 0
(FALSE), or NULL. These
operations work for both numbers and strings. Strings are
automatically converted to numbers and numbers to strings as
necessary.
以下关系比较运算符不仅可以用于比较标量操作数,还可以用于比较行操作数:The following relational comparison operators can be used to compare not only scalar operands, but row operands:
= > < >= <= <> !=
本节后面对这些操作符的描述详细说明了它们如何与行操作数一起使用。有关在行子查询上下文中进行行比较的更多示例,请参见第 15.2.15.5 节,“行子查询”。The descriptions for those operators later in this section detail how they work with row operands. For additional examples of row comparisons in the context of row subqueries, see Section 15.2.15.5, “Row Subqueries”.
本节中的一些函数返回的值不仅限于 1(TRUE)、0(FALSE)或 NULL。LEAST() 和 GREATEST() 就是这样的函数示例;第 14.3 节,“表达式求值中的类型转换” 介绍了这些函数及类似函数在进行比较操作以确定返回值时的规则。Some of the functions in this section return values other than
1 (TRUE),
0 (FALSE), or
NULL. LEAST()
and GREATEST() are examples of
such functions; Section 14.3, “Type Conversion in Expression Evaluation”, describes the
rules for comparison operations performed by these and similar
functions for determining their return values.
在以前的 MySQL 版本中,当评估包含 LEAST() 或 GREATEST() 的表达式时,服务器会尝试猜测函数使用的上下文,并将函数的参数强制转换为整个表达式的数据类型。例如,LEAST("11",
"45", "2") 的参数会被作为字符串进行评估和排序,因此该表达式返回 "11"。In previous versions of MySQL, when evaluating an expression
containing LEAST() or
GREATEST(), the server attempted to guess
the context in which the function was used, and to coerce the
function's arguments to the data type of the expression
as a whole. For example, the arguments to LEAST("11",
"45", "2") are evaluated and sorted as strings, so
that this expression returns "11".
该函数使用提供的参数执行,仅在参数不全为相同类型时才进行数据类型转换。任何由使用返回值的表达式强制要求的类型转换,现在都在函数执行后进行。这意味着 LEAST("11", "45", "2") +
0 会计算为 "11" + 0,因此结果为整数 11。The function is executed using the arguments as provided,
performing data type conversions to one or more of the
arguments if and only if they are not all of the same type.
Any type coercion mandated by an expression that makes use of
the return value is now performed following function
execution. This means that LEAST("11", "45", "2") +
0 evaluates to "11" + 0 and thus
to integer 11.
要将一个值转换为特定类型以进行比较,可以使用 CAST() 函数。字符串值可以使用 CONVERT() 转换为不同的字符集。参见 第 14.10 节,“转换函数和操作符”。To convert a value to a specific type for comparison purposes,
you can use the CAST() function.
String values can be converted to a different character set
using CONVERT(). See
Section 14.10, “Cast Functions and Operators”.
默认情况下,字符串比较不区分大小写,并使用当前字符集。默认字符集是 utf8mb4。By default, string comparisons are not case-sensitive and use
the current character set. The default is
utf8mb4.
相等:Equal:
mysql>
SELECT 1 = 0;-> 0 mysql>SELECT '0' = 0;-> 1 mysql>SELECT '0.0' = 0;-> 1 mysql>SELECT '0.01' = 0;-> 0 mysql>SELECT '.01' = 0.01;-> 1对于行比较,
(a, b) = (x, y)等价于:For row comparisons,(a, b) = (x, y)is equivalent to:(a = x) AND (b = y)
NULL-safe equal. This operator performs an equality comparison like the=operator, but returns1rather thanNULLif both operands areNULL,以及0rather thanNULLif one operand isNULL.NULL-safe equal. This operator performs an equality comparison like the=operator, but returns1rather thanNULLif both operands areNULL, and0rather thanNULLif one operand isNULL.<=>操作符等同于标准 SQL 中的IS NOT DISTINCT FROM操作符。The<=>operator is equivalent to the standard SQLIS NOT DISTINCT FROMoperator.mysql>
SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL;-> 1, 1, 0 mysql>SELECT 1 = 1, NULL = NULL, 1 = NULL;-> 1, NULL, NULL对于行比较,
(a, b) <=> (x, y)等价于:For row comparisons,(a, b) <=> (x, y)is equivalent to:(a <=> x) AND (b <=> y)
不相等:Not equal:
mysql>
SELECT '.01' <> '0.01';-> 1 mysql>SELECT .01 <> '0.01';-> 0 mysql>SELECT 'zapp' <> 'zappp';-> 1对于行比较,
(a, b) <> (x, y)和(a, b) != (x, y)等价于:For row comparisons,(a, b) <> (x, y)and(a, b) != (x, y)are equivalent to:(a <> x) OR (b <> y)
小于或等于:Less than or equal:
mysql>
SELECT 0.1 <= 2;-> 1对于行比较,
(a, b) <= (x, y)等价于:For row comparisons,(a, b) <= (x, y)is equivalent to:(a < x) OR ((a = x) AND (b <= y))
小于:Less than:
mysql>
SELECT 2 < 2;-> 0对于行比较,
(a, b) < (x, y)等价于:For row comparisons,(a, b) < (x, y)is equivalent to:(a < x) OR ((a = x) AND (b < y))
大于或等于:Greater than or equal:
mysql>
SELECT 2 >= 2;-> 1对于行比较,
(a, b) >= (x, y)等价于:For row comparisons,(a, b) >= (x, y)is equivalent to:(a > x) OR ((a = x) AND (b >= y))
大于:Greater than:
mysql>
SELECT 2 > 2;-> 0对于行比较,
(a, b) > (x, y)相当于:For row comparisons,(a, b) > (x, y)is equivalent to:(a > x) OR ((a = x) AND (b > y))
expr BETWEEN min AND maxexprBETWEENminANDmax如果
expr大于或等于min且expr小于或等于max,BETWEEN返回1,否则返回0。如果所有参数类型相同,这相当于表达式(min <= expr AND expr <= max)。否则,将根据 第 14.3 节,“表达式求值中的类型转换” 中描述的规则进行类型转换,但适用于所有三个参数。Ifexpris greater than or equal tominandexpris less than or equal tomax,BETWEENreturns1, otherwise it returns0. This is equivalent to the expression(if all the arguments are of the same type. Otherwise type conversion takes place according to the rules described in Section 14.3, “Type Conversion in Expression Evaluation”, but applied to all the three arguments.min<=exprANDexpr<=max)mysql>
SELECT 2 BETWEEN 1 AND 3, 2 BETWEEN 3 and 1;-> 1, 0 mysql>SELECT 1 BETWEEN 2 AND 3;-> 0 mysql>SELECT 'b' BETWEEN 'a' AND 'c';-> 1 mysql>SELECT 2 BETWEEN 2 AND '3';-> 1 mysql>SELECT 2 BETWEEN 2 AND 'x-3';-> 0在使用
BETWEEN处理日期或时间值时,为获得最佳效果,请使用CAST()将值显式转换为所需的数据类型。示例:如果将DATETIME与两个DATE值进行比较,请将DATE值转换为DATETIME值。如果在与DATE比较时使用字符串常量,例如'2001-1-1',请将该字符串转换为DATE。For best results when usingBETWEENwith date or time values, useCAST()to explicitly convert the values to the desired data type. Examples: If you compare aDATETIMEto twoDATEvalues, convert theDATEvalues toDATETIMEvalues. If you use a string constant such as'2001-1-1'in a comparison to aDATE, cast the string to aDATE.expr NOT BETWEEN min AND maxexprNOT BETWEENminANDmax这与
NOT (expr BETWEEN min AND max)相同。This is the same asNOT (.exprBETWEENminANDmax)返回列表中第一个非
NULL的值,如果没有非NULL值,则返回NULL。Returns the first non-NULLvalue in the list, orNULLif there are no non-NULLvalues.的返回类型
COALESCE()是参数类型的聚合类型。The return type ofCOALESCE()is the aggregated type of the argument types.mysql>
SELECT COALESCE(NULL,1);-> 1 mysql>SELECT COALESCE(NULL,NULL,NULL);-> NULL查询结果是否包含任何行。Whether the result of a query contains any rows.
CREATE TABLE t (col VARCHAR(3)); INSERT INTO t VALUES ('aaa', 'bbb', 'ccc', 'eee'); SELECT EXISTS (SELECT * FROM t WHERE col LIKE 'c%'); -> 1 SELECT EXISTS (SELECT * FROM t WHERE col LIKE 'd%'); -> 0NOT EXISTS(query)NOT EXISTS(query)查询结果是否不包含任何行:Whether the result of a query contains no rows:
SELECT NOT EXISTS (SELECT * FROM t WHERE col LIKE 'c%'); -> 0 SELECT NOT EXISTS (SELECT * FROM t WHERE col LIKE 'd%'); -> 1GREATEST(value1,value2,...)GREATEST(value1,value2,...)当有两个或更多参数时,返回最大的(数值最大的)参数。参数的比较规则与
LEAST()相同。With two or more arguments, returns the largest (maximum-valued) argument. The arguments are compared using the same rules as forLEAST().mysql>
SELECT GREATEST(2,0);-> 2 mysql>SELECT GREATEST(34.0,3.0,5.0,767.0);-> 767.0 mysql>SELECT GREATEST('B','A','C');-> 'C'GREATEST()如果任何参数为NULL,则返回NULL。GREATEST()returnsNULLif any argument isNULL.expr IN (value,...)exprIN (value,...)如果
expr等于IN()列表中的任意值,则返回1(真),否则返回0(假)。Returns1(true) ifexpris equal to any of the values in theIN()list, else returns0(false).类型转换根据第 14.3 节,“表达式求值中的类型转换”中描述的规则进行,适用于所有参数。如果
IN()列表中的值不需要类型转换,它们都是相同类型的非JSON常量,且expr可以作为相同类型的值(可能在类型转换之后)与它们中的每一个进行比较,则会进行优化。列表中的值会被排序,并且expr的搜索使用二分查找,这使得IN()操作非常快速。Type conversion takes place according to the rules described in Section 14.3, “Type Conversion in Expression Evaluation”, applied to all the arguments. If no type conversion is needed for the values in theIN()list, they are all non-JSONconstants of the same type, andexprcan be compared to each of them as a value of the same type (possibly after type conversion), an optimization takes place. The values the list are sorted and the search forexpris done using a binary search, which makes theIN()operation very quick.mysql>
SELECT 2 IN (0,3,5,7);-> 0 mysql>SELECT 'wefwf' IN ('wee','wefwf','weg');-> 1IN()可以用于比较行构造器:IN()can be used to compare row constructors:mysql>
SELECT (3,4) IN ((1,2), (3,4));-> 1 mysql>SELECT (3,4) IN ((1,2), (3,5));-> 0您绝不应该在
IN()列表中混合使用带引号和不带引号的值,因为带引号的值(例如字符串)和不带引号的值(例如数字)的比较规则不同。因此,混合类型可能导致结果不一致。例如,不要像这样编写IN()表达式:You should never mix quoted and unquoted values in anIN()list because the comparison rules for quoted values (such as strings) and unquoted values (such as numbers) differ. Mixing types may therefore lead to inconsistent results. For example, do not write anIN()expression like this:SELECT val1 FROM tbl1 WHERE val1 IN (1,2,'a');
相反,应这样写:Instead, write it like this:
SELECT val1 FROM tbl1 WHERE val1 IN ('1','2','a');隐式类型转换可能产生不直观的结果:Implicit type conversion may produce nonintuitive results:
mysql>
SELECT 'a' IN (0), 0 IN ('b');-> 1, 1在这两种情况下,比较值都被转换为浮点值,每种情况下都得到 0.0,并且比较结果为 1(真)。In both cases, the comparison values are converted to floating-point values, yielding 0.0 in each case, and a comparison result of 1 (true).
IN()列表中的值的数量仅受max_allowed_packet值的限制。The number of values in theIN()list is only limited by themax_allowed_packetvalue.为了符合 SQL 标准,
IN()在以下情况下返回NULL不仅在左侧表达式为NULL时返回,而且当列表中没有找到匹配并且列表中的某个表达式为NULL.To comply with the SQL standard,IN()returnsNULLnot only if the expression on the left hand side isNULL, but also if no match is found in the list and one of the expressions in the list isNULL.IN()语法也可用于编写某些类型的子查询。请参见 第 15.2.15.3 节,“使用 ANY、IN 或 SOME 的子查询”。IN()syntax can also be used to write certain types of subqueries. See Section 15.2.15.3, “Subqueries with ANY, IN, or SOME”.expr NOT IN (value,...)exprNOT IN (value,...)这与
NOT (expr IN (value,...))相同。This is the same asNOT (.exprIN (value,...))如果
N≤N1则返回0,如果N≤N2则返回1,依此类推;如果N为NULL则返回-1。所有参数都被视为整数。要求N1≤N2≤N3≤...≤Nn才能使此函数正确工作。这是因为使用了二分查找(非常快)。Returns0ifN≤N1,1ifN≤N2and so on, or-1ifNisNULL. All arguments are treated as integers. It is required thatN1≤N2≤N3≤...≤Nnfor this function to work correctly. This is because a binary search is used (very fast).mysql>
SELECT INTERVAL(23, 1, 15, 17, 30, 44, 200);-> 3 mysql>SELECT INTERVAL(10, 1, 10, 100, 1000);-> 2 mysql>SELECT INTERVAL(22, 23, 30, 44, 200);-> 0将一个值与布尔值进行比较,其中
boolean_value可以是TRUE、FALSE或UNKNOWN。Tests a value against a boolean value, whereboolean_valuecan beTRUE,FALSE, orUNKNOWN.mysql>
SELECT 1 IS TRUE, 0 IS FALSE, NULL IS UNKNOWN;-> 1, 1, 1将一个值与布尔值进行比较,其中
boolean_value可以是TRUE、FALSE或UNKNOWN。Tests a value against a boolean value, whereboolean_valuecan beTRUE,FALSE, orUNKNOWN.mysql>
SELECT 1 IS NOT UNKNOWN, 0 IS NOT UNKNOWN, NULL IS NOT UNKNOWN;-> 1, 1, 0测试一个值是否为
NULL。Tests whether a value isNULL.mysql>
SELECT 1 IS NULL, 0 IS NULL, NULL IS NULL;-> 0, 0, 1为了与 ODBC 程序良好配合,MySQL 在使用
IS NULL时支持以下额外功能:To work well with ODBC programs, MySQL supports the following extra features when usingIS NULL:如果
sql_auto_is_null变量被设置为 1,那么在成功插入自动生成的AUTO_INCREMENT值之后,你可以通过发出如下形式的语句来找到该值:Ifsql_auto_is_nullvariable is set to 1, then after a statement that successfully inserts an automatically generatedAUTO_INCREMENTvalue, you can find that value by issuing a statement of the following form:SELECT * FROM
tbl_nameWHEREauto_colIS NULL如果该语句返回一行,则返回的值与调用
LAST_INSERT_ID()函数时返回的值相同。有关详细信息,包括多行插入后的返回值,请参见 第 14.15 节,“信息函数”。如果没有成功插入AUTO_INCREMENT值,则SELECT语句不返回任何行。If the statement returns a row, the value returned is the same as if you invoked theLAST_INSERT_ID()function. For details, including the return value after a multiple-row insert, see Section 14.15, “Information Functions”. If noAUTO_INCREMENTvalue was successfully inserted, theSELECTstatement returns no row.通过使用
IS NULL比较来检索AUTO_INCREMENT值的行为可以通过设置sql_auto_is_null = 0来禁用。参见 第 7.1.8 节,“服务器系统变量”。The behavior of retrieving anAUTO_INCREMENTvalue by using anIS NULLcomparison can be disabled by settingsql_auto_is_null = 0. See Section 7.1.8, “Server System Variables”.sql_auto_is_null的默认值为 0。The default value ofsql_auto_is_nullis 0.对于声明为
NOT NULL的DATE和DATETIME列,可以使用类似下面的语句找到特殊日期'0000-00-00':ForDATEandDATETIMEcolumns that are declared asNOT NULL, you can find the special date'0000-00-00'by using a statement like this:SELECT * FROM
tbl_nameWHEREdate_columnIS NULL这是为了让某些 ODBC 应用程序能够正常工作,因为 ODBC 不支持
'0000-00-00'日期值。This is needed to get some ODBC applications to work because ODBC does not support a'0000-00-00'date value.请参见获取自增值,以及Connector/ODBC 连接参数中
FLAG_AUTO_IS_NULL选项的说明。See Obtaining Auto-Increment Values, and the description for theFLAG_AUTO_IS_NULLoption at Connector/ODBC Connection Parameters.
测试一个值是否不是
NULL。Tests whether a value is notNULL.mysql>
SELECT 1 IS NOT NULL, 0 IS NOT NULL, NULL IS NOT NULL;-> 1, 1, 0如果
expr为NULL,ISNULL()返回1,否则返回0。IfexprisNULL,ISNULL()returns1, otherwise it returns0.mysql>
SELECT ISNULL(1+1);-> 0 mysql>SELECT ISNULL(1/0);-> 1ISNULL()可以用来代替=来测试某个值是否为NULL。(使用=将值与NULL比较总是返回NULL。)ISNULL()can be used instead of=to test whether a value isNULL. (Comparing a value toNULLusing=always yieldsNULL.)ISNULL()函数与IS NULL比较运算符有一些特殊的共同行为。请参阅IS NULL的描述。TheISNULL()function shares some special behaviors with theIS NULLcomparison operator. See the description ofIS NULL.当有两个或更多参数时,返回最小值(数值最小)的参数。使用以下规则比较参数:With two or more arguments, returns the smallest (minimum-valued) argument. The arguments are compared using the following rules:
如果任何参数为
NULL,结果为NULL。无需进行比较。If any argument isNULL, the result isNULL. No comparison is needed.如果所有参数都是整数值,则它们将作为整数进行比较。If all arguments are integer-valued, they are compared as integers.
如果至少有一个参数是双精度的,则它们作为双精度值进行比较。否则,如果至少有一个参数是
DECIMAL值,则它们作为DECIMAL值进行比较。If at least one argument is double precision, they are compared as double-precision values. Otherwise, if at least one argument is aDECIMALvalue, they are compared asDECIMALvalues.如果参数包含数字和字符串的混合,它们将作为字符串进行比较。If the arguments comprise a mix of numbers and strings, they are compared as strings.
如果任何参数是非二进制(字符)字符串,则参数将作为非二进制字符串进行比较。If any argument is a nonbinary (character) string, the arguments are compared as nonbinary strings.
在所有其他情况下,参数将作为二进制字符串进行比较。In all other cases, the arguments are compared as binary strings.
LEAST()的返回类型是比较参数类型的聚合类型。The return type ofLEAST()is the aggregated type of the comparison argument types.mysql>
SELECT LEAST(2,0);-> 0 mysql>SELECT LEAST(34.0,3.0,5.0,767.0);-> 3.0 mysql>SELECT LEAST('B','A','C');-> 'A'