EnexoOnoma
EnexoOnoma

Reputation: 8834

How to have IF conditions within a mySQL query?

I wonder if there is a way to have IF condition inside a mySQL query? What I want to do is to avoid having multiple queries.

Here is my thinking:

SELECT company, color, stock FROM mytable

if color = 'blue' : WHERE company = 5
if color = 'red' : WHERE stock = 'yes'

AND status = 'available'

order by color ASC

Thank you

Upvotes: 0

Views: 38

Answers (1)

forpas
forpas

Reputation: 164204

You can add the conditions in the WHERE clause combined with the operator OR:

SELECT company, color, stock 
FROM mytable
WHERE 
  (
    (company = 5 AND color = 'blue')
    OR
    (stock = 'yes' AND color = 'red')
  )
  AND status = 'available'
ORDER BY color ASC

Upvotes: 1

Related Questions