LXXIII LXXIII - 6 months ago 7
MySQL Question

I need an SQL query that selects from either Column A or B depending on the existence of a string in Column C

I need an SQL query that selects from Column A if Column C contains the string 'ebook'. Otherwise, select from Column B.

So something like:

IF (Table.ColumnC = "ebook") SELECT Table.ColumnA AS Publisher
ELSE SELECT Table.ColumnB AS Publisher

Answer
Select 
  case when columnC = 'e-book' 
    then columnA 
    else columnB 
  end as Publisher
from myTable;

You need a case statement

I reformatted to help show how this works.

Basically Case is a scalar (row per row) IF statement

There can be multiple conditions WHEN, similar to else if. The function goes from condition to condition, if no conditions are passed, the ELSE value is used.

There are simple and search forms of CASE Documentation

Simple CASE expression:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END 

Searched CASE expression:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END