MySQL 9.0 发行说明
parenthesized_query_expression:
( query_expression [order_by_clause] [limit_clause] )
[order_by_clause]
[limit_clause]
[into_clause]
query_expression:
query_block [set_op query_block [set_op query_block ...]]
[order_by_clause]
[limit_clause]
[into_clause]
query_block:
SELECT ... | TABLE | VALUES
order_by_clause:
ORDER BY as for SELECT
limit_clause:
LIMIT as for SELECT
into_clause:
INTO as for SELECT
set_op:
UNION | INTERSECT | EXCEPT
MySQL 9.0 根据前面的语法支持带括号的查询表达式。最简单地说,带括号的查询表达式包含一个返回结果集的 SELECT
语句或其他语句,并且后面没有可选子句
(SELECT 1);
(SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'mysql');
TABLE t;
VALUES ROW(2, 3, 4), ROW(1, -2, 3);
带括号的查询表达式还可以包含由一个或多个集合操作(例如 UNION
)链接的查询,并以任何或所有可选子句结尾
mysql> (SELECT 1 AS result UNION SELECT 2);
+--------+
| result |
+--------+
| 1 |
| 2 |
+--------+
mysql> (SELECT 1 AS result UNION SELECT 2) LIMIT 1;
+--------+
| result |
+--------+
| 1 |
+--------+
mysql> (SELECT 1 AS result UNION SELECT 2) LIMIT 1 OFFSET 1;
+--------+
| result |
+--------+
| 2 |
+--------+
mysql> (SELECT 1 AS result UNION SELECT 2)
ORDER BY result DESC LIMIT 1;
+--------+
| result |
+--------+
| 2 |
+--------+
mysql> (SELECT 1 AS result UNION SELECT 2)
ORDER BY result DESC LIMIT 1 OFFSET 1;
+--------+
| result |
+--------+
| 1 |
+--------+
mysql> (SELECT 1 AS result UNION SELECT 3 UNION SELECT 2)
ORDER BY result LIMIT 1 OFFSET 1 INTO @var;
mysql> SELECT @var;
+------+
| @var |
+------+
| 2 |
+------+
INTERSECT
的优先级高于 UNION
和 EXCEPT
,因此以下两个语句是等效的
SELECT a FROM t1 EXCEPT SELECT b FROM t2 INTERSECT SELECT c FROM t3;
SELECT a FROM t1 EXCEPT (SELECT b FROM t2 INTERSECT SELECT c FROM t3);
带括号的查询表达式也用作查询表达式,因此通常由查询块组成的查询表达式也可以由带括号的查询表达式组成
(TABLE t1 ORDER BY a) UNION (TABLE t2 ORDER BY b) ORDER BY z;
查询块可以具有尾随的 ORDER BY
和 LIMIT
子句,这些子句在外部集合操作、ORDER BY
和 LIMIT
之前应用。
您不能在不将查询块括在括号中的情况下使用尾随的 ORDER BY
或 LIMIT
,但可以使用括号以各种方式强制执行
对每个查询块强制执行
LIMIT
(SELECT 1 LIMIT 1) UNION (VALUES ROW(2) LIMIT 1); (VALUES ROW(1), ROW(2) LIMIT 2) EXCEPT (SELECT 2 LIMIT 1);
对查询块和整个查询表达式强制执行
LIMIT
(SELECT 1 LIMIT 1) UNION (SELECT 2 LIMIT 1) LIMIT 1;
对整个查询表达式强制执行
LIMIT
(不带括号)VALUES ROW(1), ROW(2) INTERSECT VALUES ROW(2), ROW(1) LIMIT 1;
混合执行:在第一个查询块和整个查询表达式上使用
LIMIT
(SELECT 1 LIMIT 1) UNION SELECT 2 LIMIT 1;
本节描述的语法受某些限制
如果括号内有另一个
INTO
子句,则查询表达式的尾随INTO
子句是不允许的。括号内的查询表达式中的
ORDER BY
或LIMIT
也应用于外部查询,其处理方式符合 SQL 标准。允许嵌套括号内的查询表达式。支持的最大嵌套级别为 63;这是在解析器执行任何简化或合并之后。
此处显示了此类语句的示例
mysql> (SELECT 'a' UNION SELECT 'b' LIMIT 2) LIMIT 3; +---+ | a | +---+ | a | | b | +---+ 2 rows in set (0.00 sec)
您应该注意,在折叠括号内的表达式主体时,MySQL 遵循 SQL 标准语义,因此较高的外部限制不能覆盖较低的内部限制。例如,
(SELECT ... LIMIT 5) LIMIT 10
最多只能返回五行。