MySQL-如果column为null,则从另一个表中检索值 [英] MySQL - retrieve a value from another table if column is null
本文介绍了MySQL-如果column为null,则从另一个表中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有一个表设置,其中包含一些值,包括名称,ID和引用另一个表ID的外键.名称可以为空.当我从该表中选择所有记录时,如果名称不为null,我想获取名称.如果是这样,我想获取外键引用的记录的名称.我可以根据需要修改数据库结构,也可以简单地更改查询.我有什么选择?
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?
推荐答案
使用 COALESCE
:
SELECT T1.ID, IFNULL(T1.name, T2.name) AS name
FROM firsttable T1
LEFT JOIN secondtable T2
ON T1.T2_id = T2.id
这篇关于MySQL-如果column为null,则从另一个表中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文