SQL:如果存在外键,则使用另一个表列替换列值

时间:2014-01-16 16:03:18

标签: mysql sql left-join

我正在查询table a每行的名称,但是,如果该行具有bID值(这将是表b的id的外键),我想替换名称值table a table b table a --------- id / bID (may be null) / name table b --------- id / name SELECT a.id as id, a.name as name, a.bid FROM `table a` as a LEFT JOIN `table b` as b ON a.bID = b.id ORDER BY id ASC 。我怎么能这样做?

{{1}}

1 个答案:

答案 0 :(得分:1)

“b”表名称上的简单ISNULL就足够了。您可以使用COALESCE代替,如果您需要,也可以使用多个参数,而不仅仅是ISNULL

SELECT a.id as id, ISNULL(b.name, a.name) as name, a.bid
FROM `table a` as a
LEFT JOIN `table b` as b ON a.bID = b.id
ORDER BY id ASC