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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With