[英]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.