Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - retrieve a value from another table if column is null

Tags:

sql

select

mysql

Let's say I have a table setup with a few values, including a name, an ID, and a foreign key that references the ID of another table. The name can be null. When I select all the records from this table, I want to get the name if it is not null. If it is, I want to get the name of the record referenced by the foreign key. I am able to modify the database structure if necessary, or I can simply change the query. What are my options?

like image 341
Fibericon Avatar asked Sep 30 '11 07:09

Fibericon


1 Answers

Use IFNULL or COALESCE:

SELECT T1.ID, IFNULL(T1.name, T2.name) AS name
FROM firsttable T1
LEFT JOIN secondtable T2
ON T1.T2_id = T2.id
like image 182
Mark Byers Avatar answered Oct 01 '22 10:10

Mark Byers