A
A
Anton B2017-10-25 18:52:49
SQL
Anton B, 2017-10-25 18:52:49

How to stop the search when one of the conditions is met?

Hello!

Выполняю первый запрос:
SELECT * FROM `table` WHERE `a` = 1 AND `b` = 2 AND `c` = 3
Если первый запрос не вернул значений, то выполняю второй запрос:
SELECT * FROM `table` WHERE `a` = 1 AND `b` = 2
Если второй запрос не вернул значений, то выполняю третий запрос:
SELECT * FROM `table` WHERE `a` = 1

Can this be done in one request?
SELECT * FROM `table` WHERE 
IF (`a` = 1 AND `b` = 2 AND `c` = 3) // вернуть значения, прекратить поиск
ELSE IF ( `a` = 1 AND `b` = 2) // вернуть значения, прекратить поиск
ELSE IF (`a` = 1) // вернуть значения, прекратить поиск

Thanks for answers!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2017-10-26
@Alex1OPS

That's the condition

stop searching
means SQL will not quit. However, it is possible to pile up a similar construction, which will cost for one access to the table (the query was written in Oracle SQL, in other dialects, I believe, there is something similar):
select * from  (
  select t.*, 
         (case
           when t.`a` = 1 and t.`b` = 2 and t.`c` = 3 then 0
           when t.`a` = 1 and t.`b` = 2 then 1
           when t.`a` = 1 then 2
         end) as rnk,
         min((case
           when t.`a` = 1 and t.`b` = 2 and t.`c` = 3 then 0
           when t.`a` = 1 and t.`b` = 2 then 1
           when t.`a` = 1 then 2
         end)) over () as min_rnk
    from `table` t
   where (t.`a` = 1 and t.`b` = 2 and t.`c` = 3)
      or (t.`a` = 1 and t.`b` = 2)
      or (t.`a` = 1)) ta
where ta.rnk = ta.min_rnk

Update : As Google kindly suggested to me, you probably have MySQL :) I don't know how useful my answer will be, but I'll leave it here.

D
d-stream, 2017-10-26
@d-stream

In principle
, select top 1 - if you need some result
if exists - if you need the fact of existence

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question