Scalar or column subqueries return a single value or a column of values. 标量或列子查询返回单个值或一列值。A row subquery is a subquery variant that returns a single row and can thus return more than one column value. 行子查询是一个子查询变量,它返回一行,因此可以返回多个列值。Legal operators for row subquery comparisons are:行-子查询比较的合法运算符为:
= > < >= <= <> != <=>
Here are two examples:
SELECT * FROM t1 WHERE (col1,col2) = (SELECT col3, col4 FROM t2 WHERE id = 10); SELECT * FROM t1 WHERE ROW(col1,col2) = (SELECT col3, col4 FROM t2 WHERE id = 10);
For both queries, if the table 对于这两个查询,如果表t2
contains a single row with id = 10
, the subquery returns a single row. t2
包含id=10
的单行,则子查询返回单行。If this row has 如果此行的col3
and col4
values equal to the col1
and col2
values of any rows in t1
, the WHERE
expression is TRUE
and each query returns those t1
rows. col3
和col4
值等于t1
中任何行的col1
和col2
值,则WHERE
表达式为TRUE
,并且每个查询都返回这些t1
行。If the 如果t2
row col3
and col4
values are not equal the col1
and col2
values of any t1
row, the expression is FALSE
and the query returns an empty result set. t2
行的col3
和col4
值不等于任何t1
行的col1
和col2
值,则表达式为FALSE
,查询返回空结果集。The expression is unknown (that is, 如果子查询不生成行,则表达式是未知的(即NULL
) if the subquery produces no rows. NULL
)。An error occurs if the subquery produces multiple rows because a row subquery can return at most one row.如果子查询生成多行,则会发生错误,因为行子查询最多只能返回一行。
For information about how each operator works for row comparisons, see Section 12.4.2, “Comparison Functions and Operators”.有关每个运算符如何进行行比较的信息,请参阅第12.4.2节,“比较函数和运算符”。
The expressions 表达式(1,2)
and ROW(1,2)
are sometimes called row constructors. (1,2)
和ROW(1,2)
有时称为行构造函数。The two are equivalent. 两者是等价的。The row constructor and the row returned by the subquery must contain the same number of values.行构造函数和子查询返回的行必须包含相同数量的值。
A row constructor is used for comparisons with subqueries that return two or more columns. 行构造函数用于与返回两列或更多列的子查询进行比较。When a subquery returns a single column, this is regarded as a scalar value and not as a row, so a row constructor cannot be used with a subquery that does not return at least two columns. 当子查询返回单个列时,它被视为标量值而不是行,因此行构造函数不能与至少不返回两列的子查询一起使用。Thus, the following query fails with a syntax error:因此,以下查询失败并出现语法错误:
SELECT * FROM t1 WHERE ROW(1) = (SELECT column1 FROM t2)
Row constructors are legal in other contexts. 行构造函数在其他上下文中是合法的。For example, the following two statements are semantically equivalent (and are handled in the same way by the optimizer):例如,以下两个语句在语义上是等价的(优化器以相同的方式处理它们):
SELECT * FROM t1 WHERE (column1,column2) = (1,1); SELECT * FROM t1 WHERE column1 = 1 AND column2 = 1;
The following query answers the request, “find all rows in table 下面的查询回答了“查找表t1
that also exist in table t2
”:t1
中也存在于表t2
中的所有行”的请求:
SELECT column1,column2,column3 FROM t1 WHERE (column1,column2,column3) IN (SELECT column1,column2,column3 FROM t2);
For more information about the optimizer and row constructors, see Section 8.2.1.22, “Row Constructor Expression Optimization”有关优化器和行构造函数的更多信息,请参阅第8.2.1.22节,“行构造函数表达式优化”。