Khoa Trumcuoi
Khoa Trumcuoi

Reputation: 33

MYSQL IF NOT LIKE A THEN LIKE B

i want to make a sql query l but how do I perform an IF...THEN in an SQL SELECT statement like: " select name from table1,table2 where if( name like a then name like a ) else name like b"

Upvotes: 0

Views: 3228

Answers (4)

Jerric Calosor
Jerric Calosor

Reputation: 36

Ever tried mysql stored procedure http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx?

And you may want to check this out: using "if" and "else" Stored Procedures MySQL

Hope this helps! :)

Upvotes: 0

sgeddes
sgeddes

Reputation: 62851

MySQL supports IF statements and CASE statements. Try something like this assuming a and b are columns in one of your tables and name is a column in your other table:

 select name 
    from table1,table2
    where name like 
       case 
          when name like a 
          then a
          else b
       end

And some sample fiddle: http://sqlfiddle.com/#!2/c6ce6/1

You may be wanting to use '%' with your LIKE query -- if so, CONCAT accordingly. This same logic can be used with string values instead if needed.

Please post your table structure, sample data, and desired output so we can fully understand your question though and provide the best answer.

Upvotes: 1

Peter Wooster
Peter Wooster

Reputation: 6089

SQL isn't a programming language, it doesn't have if, then, else etc. If the required condition can be expressed in set operations such as AND and OR you can do it.

Otherwise you need to write a Stored Procedure, Stored Function or Stored Routine. See http://dev.mysql.com/doc/refman/5.1/en/stored-routines.html, which will allow you to write procedural code. The set operations are usually much faster.

Upvotes: 1

ruakh
ruakh

Reputation: 183456

You can use the OR operator, which connects two Boolean clauses:

WHERE name LIKE ...
   OR name LIKE ...

Note that OR has lower precedence than AND, so if you want to combine this with other restrictions, you'll need to use parentheses; for example:

WHERE ( name LIKE '%a%' OR name LIKE '%b%' )
  AND id < 1000

Upvotes: 2

Related Questions