Run a SELECT inside an IF in SQL?

Asked

Viewed 107 times

0

I would like to know how to execute an IF condition with SELECT, I am still studying about SQL so in the example I will try to pass only the idea because the syntax will probably not be correct.

IF (SELECT * FROM tb_ticker WHERE Ticker = '{$variavelPHP}')          //se a variável que é uma string for exatamente igual a um campo da coluna Ticker
   SELECT * FROM tb_ticker WHERE Ticker = '{$variavelPHP}'            //ela irá me retornar ele mesmo, o valor exato
ELSE
   SELECT * FROM tb_ticker WHERE Ticker LIKE '%{$variavelPHP}%' 
   OR Empresa LIKE '%{$variavelPHP}%' ORDER BY Ticker ASC LIMIT 20    //senão ele irá me retornar os possíveis nomes que podem estar em 2 colunas da mesma tabela ordenado pela coluna Ticker com limite de 20 campos

1 answer

1


You can use EXISTS together with other filters.

Example:

SELECT * 
  FROM tb_ticker 
 WHERE ((EXISTS (SELECT 1 FROM tb_ticker WHERE Ticker = '{$variavelPHP}')
   AND Ticker = '{$variavelPHP}')
    OR (NOT EXISTS (SELECT 1 FROM tb_ticker WHERE Ticker = '{$variavelPHP}') 
   AND (Ticker LIKE '%{$variavelPHP}%' 
    OR Empresa LIKE '%{$variavelPHP}%')))
 ORDER BY Ticker ASC LIMIT 20;

See spinning here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.