如果子查询的结果为NULL,则整个查询失败

时间:2013-12-06 10:23:07

标签: php mysql sql select subquery

我遇到的情况是我需要使用同一个表的有效数据

生成包含随机数据的行

我已使用rand($min, $max)$min = 1$max = [SELECT MAX(ID) FROM patient] - 1

通过php 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
ID > 26360

现在在上面查询26360的>中,该随机数和{{1}}用于避免26360被删除的可能性

问题:

如果任何子查询返回没有结果,则完成查询失败并且不返回任何内容。

3 个答案:

答案 0 :(得分:6)

试试这个:

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

答案 1 :(得分:4)

将您的所有查询更改为:

SELECT FirstName FROM patient WHERE ID > 11445 AND FirstName != '' UNION SELECT NULL FROM DUAL LIMIT 1

即。添加UNION SELECT NULL FROM DUAL(在所有子查询中)

答案 2 :(得分:0)

您需要使用LEFT OUTER JOIN:

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
)