开发者

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

Let's say I have a table se开发者_JAVA技巧tup 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


Use ISNULL for sql

SELECT T1.ID, ISNULL(T1.name, T2.name) AS name
FROM firsttable T1
LEFT JOIN secondtable T2
ON T1.T2_id = T2.id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜