13.2.10.4 Parenthesized Query Expressions带圆括号的查询表达式

parenthesized_query_expression:
    ( query_expression [order_by_clause] [limit_clause] )
      [order_by_clause]
      [limit_clause]
      [into_clause]
query_expression:
query_block [UNION query_block [UNION query_block ...]]
      [order_by_clause]
      [limit_clause]
      [into_clause]
query_block:
    SELECT ...             (see Section 13.2.10, “SELECT Statement”)
order_by_clause:
    ORDER BY as for SELECT (see Section 13.2.10, “SELECT Statement”)
limit_clause:
    LIMIT as for SELECT    (see Section 13.2.10, “SELECT Statement”)
into_clause:
    INTO as for SELECT     (see Section 13.2.10, “SELECT Statement”)

MySQL 8.0.22 and higher supports parenthesized query expressions according to the preceding syntax. MySQL8.0.22及更高版本根据前面的语法支持带圆括号的查询表达式。At its simplest, a parenthesized query expression contains a single SELECT and no following optional clauses:最简单的情况是,带圆括号的查询表达式只包含一个SELECT子句,不包含以下可选子句:

(SELECT 1);
(SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'mysql');

A parenthesized query expression can also contain a UNION comprising multiple SELECT statements, and end with any or all of the optional clauses:带圆括号的查询表达式还可以包含由多个SELECT语句组成的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 |
+------+

Parenthesized query expressions are also used as query expressions, so a query expression, usually composed of query blocks, may also consist of parenthesized query expressions:带圆括号的查询表达式也可用作查询表达式,因此通常由查询块组成的查询表达式也可能由带圆括号的查询表达式组成:

(SELECT * FROM t1 ORDER BY a) UNION (SELECT * FROM t2 ORDER BY b) ORDER BY z;

Query blocks may have trailing ORDER BY and LIMIT clauses, which are applied before the outer UNION and ORDER BY and LIMIT.查询块可能有ORDER BYLIMIT子句,它们应用于外部UNIONORDER BYLIMIT之前。

You cannot have a query block with a trailing ORDER BY or LIMIT, without wrapping it in parentheses, but parentheses may be used for enforcement in various ways:如果查询块的尾部带有ORDER BYLIMIT,则不能将其括在圆括号中,但圆括号可用于以各种方式强制执行:

The syntax described in this section is subject to certain restrictions:本节中描述的语法受某些限制: