Reputation: 5069
Given two subquery tables t1 and t2, how can I return t2 if and only if t1 returned empty rows?
Edit: Added example
T1
SELECT *
FROM common_table
WHERE language_id = 1
T2
SELECT *
FROM common_table
WHERE language_id = 2
Basically what I am doing is that in case the T1 return empty rows, I would like it to execute T2 and return those rows. Now, I am fully aware that I can do this in PHP but the query is a subquery and I would rather let SQL (not PHP) code handle it.
Upvotes: 4
Views: 4101
Reputation: 57063
SELECT *
FROM common_table
WHERE language_id = 1
UNION
SELECT *
FROM common_table
WHERE language_id = 2
AND NOT EXISTS (
SELECT *
FROM common_table AS T2
WHERE T2.language_id = 1
);
Upvotes: 0
Reputation: 64655
Select ...
From common_table
Where language_id = 1
Or (
language_id = 2
And Not Exists (
Select 1
From common_table
Where language_id = 1
)
)
Upvotes: 3
Reputation: 34625
My MySql knowledge is a bit rusty and I think this should work.
SELECT * FROM common_table
WHERE language_id = 2 and
0 = ( SELECT count(*) FROM common_table
WHERE language_id = 1
) ;
Upvotes: 1
Reputation: 2928
In MSSQL I can do something like
If EXISTS (SELECT * FROM common_table WHERE language_id = 1)
BEGIN
SELECT * FROM common_table WHERE language_id = 1
END ELSE BEGIN
SELECT * FROM common_table WHERE language_id = 2
END
Should be the same in mySQL or similar
Upvotes: 2