user2168066 user2168066 - 1 year ago 77
MySQL Question

Conditional select statement using 3 tables

I am trying to do a conditional case statement and am not sure if sql can perform this.
I need to select the ID from Table A, and the Name from the corresponding ID in table B. If the Name in Table B is NULL, i need to select the Name from Table C. I am not sure how to do this using a CASE or if it is possible, any help is greatly appriciated.

Table A Table B Table C
ID ID2 ID2 Name ID2 Name
________ ___________ ___________
1 3 1 bill 1 NULL
2 2 2 steve 2 NULL
3 1 3 NULL 3 george

Answer Source

Use IFNULL() to select the appropriate column from B or C.

JOIN b ON = b.id2
JOIN c ON = c.id2

If the matching rows could be missing from B or C, use LEFT JOIN instead of JOIN.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download