Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL the whole query fails if result of sub query is NULL

I have a situation where I need to generate rows with random data out of the same table's valid data

I have generated ID by php rand($min, $max) function with $min = 1 and $max = [SELECT MAX(ID) FROM patient] - 1

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

Now in the ID > 26360 from the above query 26360 is that random number and > is used to avoid the possibility if 26360 was deleted

PROBLEM:

if any of the sub query returns no result complete query fails and return nothing.

like image 288
zzlalani Avatar asked Dec 06 '13 10:12

zzlalani


People also ask

What happens when a subquery result is empty?

For a table subquery: If the subquery returns no rows, the result is an empty set of values, so for instance the IN operation would always return false.

What will be returned by a query if it has a subquery and that subquery returns NULL?

If a subquery (inner query) returns a null value to the outer query, the outer query will not return any rows when using certain comparison operators in a WHERE clause.

What is the output of this query if the subquery returns no rows?

The subquery is evaluated to determine whether it returns any rows. If it returns at least one row, the result of EXISTS is “true”; if the subquery returns no rows, the result of EXISTS is “false”.

What is sub query in MySQL?

A subquery is a SELECT statement within another statement. All subquery forms and operations that the SQL standard requires are supported, as well as a few features that are MySQL-specific.


1 Answers

Try this:

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
like image 159
Saharsh Shah Avatar answered Sep 19 '22 19:09

Saharsh Shah