簡體   English   中英

SQL:如果存在外鍵,則用另一個表列替換列值

[英]SQL: Replacing a column value with another tables column, if a foreign key exists

我正在查詢table a中每一行的名稱,但是,如果該行具有bID值(這將是表b的id的外鍵),我想用table b替換table a的名稱值。 我怎樣才能做到這一點?

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

在“ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM