#### 13.2.10.4 带括号的查询表达式

[](<>)[](<>)[](<>)[](<>)[](<>)

```
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 及更高版本根据上述语法支持带括号的查询表达式。最简单的，带括号的查询表达式包含一个[`选择`](select.html)并且没有以下可选条款：

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

带括号的查询表达式还可以包含[`联盟`](union.html)包括多个[`选择`](select.html)语句，并以任何或所有可选子句结尾：

```
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 |
+------+
```

带括号的查询表达式也用作查询表达式，因此通常由查询块组成的查询表达式也可以由带括号的查询表达式组成：

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

查询块可能有尾随`订购方式`和`限制`子句，在外层之前应用`联盟`和`订购方式`和`限制`.

您不能有一个带有尾随的查询块`订购方式`要么`限制`, 不用括号括起来，但括号可用于以各种方式强制执行：

-   执行`限制`在每个查询块上：

    ```
    (SELECT 1 LIMIT 1) UNION (SELECT 2 LIMIT 1);
    ```

-   执行`限制`在查询块和整个查询表达式上：

    ```
    (SELECT 1 LIMIT 1) UNION (SELECT 2 LIMIT 1) LIMIT 1;
    ```

-   执行`限制`在整个查询表达式上（没有括号）：

    ```
    SELECT 1 UNION SELECT 2 LIMIT 1;
    ```

-   混合执法：`限制`在第一个查询块和整个查询表达式上：

    ```
    (SELECT 1 LIMIT 1) UNION SELECT 2 LIMIT 1;
    ```

    本节中描述的语法受到某些限制：

-   如果`订购方式`出现在带括号的查询表达式中，也应用于外部查询，结果是未定义的，并且可能在 MySQL 的未来版本中发生变化。如果`限制`出现在带括号的查询表达式中，也应用于外部查询。

-   尾随`进入`如果有另一个查询表达式的子句，则不允许`进入`括号内的子句。

-   带括号的查询表达式不允许多级`订购方式`要么`限制`操作。例如：

    ```
    mysql> (SELECT 'a' UNION SELECT 'b' LIMIT 1) LIMIT 2;
    ERROR 1235 (42000): This version of MySQL doesn't yet support 'parenthesized
    query expression with more than one external level of ORDER/LIMIT operations'
    ```
