MySQL 标量子查询返回什么样的输出?在 MySQL 查询中使用它有哪些限制?
mysqlmysqli database
MySQL 标量子查询从一行返回一个列值,我们可以在允许单列的情况下使用它。以下是标量子查询返回除一行以外的值的情况 −
情况 1 − 当它返回 0 行时
如果子查询返回 0 行,则标量子查询表达式的值将为 NULL。
情况 2 − 当它返回多行时
如果子查询返回多行,则由于标量子查询的属性,MySQL 将返回错误。
可以借助使用下表中数据的示例来理解 −
mysql> Select * from Customers; +-------------+----------+ | Customer_Id | Name | +-------------+----------+ | 1 | Rahul | | 2 | Yashpal | | 3 | Gaurav | | 4 | Virender | +-------------+----------+ 4 rows in set (0.00 sec) mysql> Select * from Reservations; +------+-------------+------------+ | ID | Customer_id | Day | +------+-------------+------------+ | 1 | 1 | 2017-12-30 | | 2 | 2 | 2017-12-28 | | 3 | 2 | 2017-12-29 | | 4 | 1 | 2017-12-25 | | 5 | 3 | 2017-12-26 | +------+-------------+------------+ 5 rows in set (0.00 sec)
现在,以下查询将为一行返回一个列值 −
mysql> Select Name from Customers WHERE customer_id = (Select Customer_id FROM reservations where id = 3); +---------+ | Name | +---------+ | Yashpal | +---------+ 1 row in set (0.00 sec)
现在,假设子查询返回 0 行,则意味着标量子查询表达式的值为 NULL。它显示在以下查询 −
mysql> Select Name from Customers WHERE customer_id = (Select Customer_id FROM reservations where id = 10); Empty set (0.00 sec)
从上面的结果集中我们可以看到,MySQL 返回空集,即 0 行,因为标量子查询表达式的值为 NULL(没有等于 10 的 id)。
在 MySQL 查询中使用标量子查询的限制是,我们只能使用标量子查询和仅允许文字值的语句。例如,我们知道 LIMIT 需要文字整数参数,因此我们不能使用标量子查询来提供这些值。