如果子查询的结果为 NULL,MySQL 整个查询将失败
Posted
技术标签:
【中文标题】如果子查询的结果为 NULL,MySQL 整个查询将失败【英文标题】:MySQL the whole query fails if result of sub query is NULL 【发布时间】:2013-12-23 15:52:36 【问题描述】:我有一种情况,我需要从同一张表的有效数据中生成包含随机数据的行
我已经通过$min = 1
和$max = [SELECT MAX(ID) FROM patient] - 1
的php rand($min, $max)
函数生成ID
Select
tblFirstName.FirstName,
tblLastName.LastName,
tblBirthDate.BirthDate,
tblLocation.Location
From
(SELECT FirstName FROM patient WHERE ID > 11445 AND FirstName != '' LIMIT 1) AS tblFirstName,
(SELECT LastName FROM patient WHERE ID > 74964 AND LastName != '' LIMIT 1) AS tblLastName,
(SELECT BirthDate FROM patient WHERE ID > 26360 LIMIT 1) AS tblBirthDate,
(SELECT Location FROM patient WHERE ID > 68356 AND Location != '' LIMIT 1) AS tblLocation
现在在上述查询的ID > 26360
中,26360 是随机数,>
用于避免删除 26360 的可能性
问题:
如果任何子查询没有返回结果,则完整查询失败并且什么也不返回。
【问题讨论】:
【参考方案1】:试试这个:
SELECT (SELECT FirstName FROM patient WHERE ID > 11445 AND FirstName != '' LIMIT 1) AS tblFirstName,
(SELECT LastName FROM patient WHERE ID > 74964 AND LastName != '' LIMIT 1) AS tblLastName,
(SELECT BirthDate FROM patient WHERE ID > 26360 LIMIT 1) AS tblBirthDate,
(SELECT Location FROM patient WHERE ID > 68356 AND Location != '' LIMIT 1) AS tblLocation
【讨论】:
【参考方案2】:将所有查询更改为:
SELECT FirstName FROM patient WHERE ID > 11445 AND FirstName != '' UNION SELECT NULL FROM DUAL LIMIT 1
即添加 UNION SELECT NULL FROM DUAL(在所有子查询中)
【讨论】:
【参考方案3】:你需要使用左外连接:
Select
tblFirstName.FirstName,
tblLastName.LastName,
tblBirthDate.BirthDate,
tblLocation.Location
From
(SELECT FirstName FROM patient WHERE ID > 11445 AND FirstName != '' LIMIT 1) AS tblFirstName
LEFT JOIN
(
(SELECT LastName FROM patient WHERE ID > 74964 AND LastName != '' LIMIT 1) AS tblLastName, (SELECT BirthDate FROM patient WHERE ID > 26360 LIMIT 1) AS tblBirthDate,
(SELECT Location FROM patient WHERE ID > 68356 AND Location != '' LIMIT 1) AS tblLocation
)
【讨论】:
以上是关于如果子查询的结果为 NULL,MySQL 整个查询将失败的主要内容,如果未能解决你的问题,请参考以下文章