Thursday, 29 August 2013

If column value is null, use other column

If column value is null, use other column

First of all, don't scold me for trying to do this - my boss wants me to
dump a list of data from across many tables into a single CSV file.
This CSV contains two categories of people combined into a single sheet:
permanent staff, and contractors.
Some values are obtained differently depending on which category you
belong to. For example, if you are a contractor, your job description is
in contractors.job. If you are permanent, the job description is in
roles.description where roles.id = staff.role.
So I tried (something like) this:
SELECT
stuff,
(CASE
WHEN c.blended_role IS NULL THEN
r.blended_role
ELSE
c.blended_role
END) as `Job Description`,
morestuff
FROM
everyone e
LEFT JOIN contractors c
ON c.id = e.id
LEFT JOIN staff s
ON s.id = e.id
LEFT JOIN roles r
ON r.id = s.role
But I got a syntax error
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near 'stuff, (CASE
WHEN c.blended_role IS NULL THEN r.blended_role EL` at line 2
Can anyone suggest an alternative?

No comments:

Post a Comment