Jordan Ramstad
Jordan Ramstad

Reputation: 179

MySQL WHERE with conditions/priority condtion

This one is a weird one that I just can't seem to wrap my head around.

Basically I need to search based on a value that has an override. So there are 2 columns with essentially the same content. One is updated automatically and one is manual. If the automatic one is not available it will use the manual, and if the manual is not available it will use the automatic one. Lastly if both are available it will use the automatic unless and "override" flag is enabled (probably a third column).

What I need to do is search based on that parameter as if it were one field, using the set of priorities on the columns. So here is an example WHERE statement, but I do not know what might be the correct syntax to use.

WHERE (isset(width)?(width_override?o_width:width):o_width) = {query}

Upvotes: 1

Views: 782

Answers (2)

Barmar
Barmar

Reputation: 780724

Use the IF function.

WHERE IF(width IS NOT NULL, IF(width_override, o_width, width),
                            o_width) = {query}

Upvotes: 2

artfulrobot
artfulrobot

Reputation: 21397

I think you're looking for COALESCE():

SELECT COALESCE(overridden_width_col, automatic_width_col) width
  FROM yourtable
 WHERE COALESCE(overridden_width_col, automatic_width_col) = %param

COALESCE() will return the first non-NULL parameter. overridden_width_col is set to NULL, it will use automatic_width_col.

Upvotes: 2

Related Questions