开发者

Do a query only if there are no results on previous query

开发者 https://www.devze.com 2023-02-01 01:20 出处:网络
I do this query(1): (1)SELECT * FROM t1 WHERE title LIKE \'key%\' LIMIT 1 I need to do a second(2) query only if this previous query has no results

I do this query(1):

(1)SELECT * FROM t1 WHERE title LIKE 'key%' LIMIT 1

I need to do a second(2) query only if this previous query has no results

(2)SELECT * FROM t1 WHERE title LIKE '%key%' LIMIT 1

basically i need only 1 row who got the most close title to my key.

Atm i am using an UNION query with a custom field to order开发者_开发问答 it and a LIMIT 1. Problem is I don't want to do the others query if already the first made the result.

Thanks


There isn't a standard way to say 'execute query Q2 if and only if query Q1 returns nothing' in a single SQL statement.

The moderately close approach would be:

SELECT * FROM t1 WHERE title LIKE 'key%' LIMIT 1
UNION
SELECT * FROM t1 WHERE title LIKE '%key%'
   AND NOT EXISTS (SELECT * FROM t1 WHERE title LIKE 'key%')
 LIMIT 1

The issue is whether the optimizer would be intelligent enough to realize that the NOT EXISTS sub-query is the first half of the UNION.

0

精彩评论

暂无评论...
验证码 换一张
取 消