13.2.11.1 The Subquery as Scalar Operand作为标量操作数的子查询

In its simplest form, a subquery is a scalar subquery that returns a single value. 在最简单的形式中,子查询是返回单个值的标量子查询。A scalar subquery is a simple operand, and you can use it almost anywhere a single column value or literal is legal, and you can expect it to have those characteristics that all operands have: a data type, a length, an indication that it can be NULL, and so on. 标量子查询是一个简单的操作数,您几乎可以在任何单个列值或文字合法的地方使用它,并且您可以期望它具有所有操作数都具有的特性:数据类型、长度、可以为NULL的指示,等等。For example:例如:

CREATE TABLE t1 (s1 INT, s2 CHAR(5) NOT NULL);
INSERT INTO t1 VALUES(100, 'abcde');
SELECT (SELECT s2 FROM t1);

The subquery in this SELECT returns a single value ('abcde') that has a data type of CHAR, a length of 5, a character set and collation equal to the defaults in effect at CREATE TABLE time, and an indication that the value in the column can be NULL. SELECT中的子查询返回一个值('abcde'),该值的数据类型为CHAR,长度为5,字符集和排序规则等于创建表时生效的默认值,并指示列中的值可以为NULLNullability of the value selected by a scalar subquery is not copied because if the subquery result is empty, the result is NULL. 不会复制标量子查询所选值的可空性,因为如果子查询结果为空,则结果为NULLFor the subquery just shown, if t1 were empty, the result would be NULL even though s2 is NOT NULL.对于刚才显示的子查询,如果t1为空,则结果将为NULL,即使s2NOT NULL

There are a few contexts in which a scalar subquery cannot be used. 有一些上下文中不能使用标量子查询。If a statement permits only a literal value, you cannot use a subquery. 如果语句只允许文本值,则不能使用子查询。For example, LIMIT requires literal integer arguments, and LOAD DATA requires a literal string file name. 例如,LIMIT需要文本整数参数,LOAD DATA需要文本字符串文件名。You cannot use subqueries to supply these values.不能使用子查询提供这些值。

When you see examples in the following sections that contain the rather spartan construct (SELECT column1 FROM t1), imagine that your own code contains much more diverse and complex constructions.当您在下面的小节中看到包含相当简单的构造(SELECT column1 FROM t1)的示例时,请想象您自己的代码包含更加多样化和复杂的构造。

Suppose that we make two tables:假设我们做两个表:

CREATE TABLE t1 (s1 INT);
INSERT INTO t1 VALUES (1);
CREATE TABLE t2 (s1 INT);
INSERT INTO t2 VALUES (2);

Then perform a SELECT:然后执行SELECT

SELECT (SELECT s1 FROM t2) FROM t1;

The result is 2 because there is a row in t2 containing a column s1 that has a value of 2.结果是2,因为t2中有一行包含值为2的列s1

In MySQL 8.0.19 and later, the preceding query can also be written like this, using TABLE:在MySQL 8.0.19及更高版本中,前面的查询也可以这样编写,使用TABLE

SELECT (TABLE t2) FROM t1;

A scalar subquery can be part of an expression, but remember the parentheses, even if the subquery is an operand that provides an argument for a function. 标量子查询可以是表达式的一部分,但请记住括号,即使子查询是为函数提供参数的操作数也是如此。For example:例如:

SELECT UPPER((SELECT s1 FROM t1)) FROM t2;

The same result can be obtained in MySQL 8.0.19 and later using SELECT UPPER((TABLE t1)) FROM t2.在MySQL 8.0.19和更高版本中,可以使用SELECT UPPER((TABLE t1)) FROM t2获得相同的结果。