Home >Database >Mysql Tutorial >Can UNION ALL with LIMIT 1 Efficiently Simulate Sequential Queries?
Sequential Selective Queries Using UNION ALL
Problem:
Seeking a single row in a database table with progressively reduced search criteria. For example:
SELECT * FROM image WHERE name LIKE 'text' AND group_id = 10 LIMIT 1
If no result is obtained, execute:
SELECT * FROM image WHERE name LIKE 'text' LIMIT 1
If still no result, execute:
SELECT * FROM image WHERE group_id = 10 LIMIT 1
Can this process be performed with a single expression?
Solution:
SELECT * FROM image WHERE name = 'name105' AND group_id = 10 UNION ALL SELECT * FROM image WHERE name = 'name105' UNION ALL SELECT * FROM image WHERE group_id = 10 LIMIT 1;
Explanation:
Generic Solution:
The above approach can be generalized for any number of search parameters by adding additional SELECT statements to the UNION ALL chain.
Considerations for Sorted Results:
Since the LIMIT clause applies to the entire result, sorting is not particularly useful because only the first row will be returned.
The above is the detailed content of Can UNION ALL with LIMIT 1 Efficiently Simulate Sequential Queries?. For more information, please follow other related articles on the PHP Chinese website!