有兩種方法可以做到這一點,一個是case語句,另一種是用內嵌表。我更喜歡內聯表,它更快。您像加入其他表一樣加入它,並使用UNION ALL構造表。就像這樣:
SELECT t.dept, coalesce(type_translate.name, 'no name') as name
FROM team t
LEFT JOIN typetable ON typetable.id = t.team_id
LEFT JOIN (
SELECT '01' as lookup, 'type01' as name
UNION ALL
SELECT '02', 'type02'
UNION ALL
SELECT '03', 'type03'
UNION ALL
SELECT '04', 'type04'
UNION ALL
SELECT '05', 'type05'
UNION ALL
SELECT '06', 'type06'
UNION ALL
SELECT '06', 'type07'
) type_translate ON left(typetable.type,2) = type_translate.lookup
如果您使用的是更標準的DB(如SQL Server,DB2,甲骨文,進展情況等),您可以使用值表的構造函數,而不是UNION ALL - 同樣的事情但更好的語法。
SELECT t.dept, coalesce(type_translate.name, 'no name') as name
FROM team t
LEFT JOIN typetable ON typetable.id = t.team_id
LEFT JOIN (
VALUES
('01', 'type01'),
('02', 'type02'),
('03', 'type03'),
('04', 'type04'),
('05', 'type05'),
('06', 'type06'),
('07', 'type07')
) AS type_translate(lookup,name) ON left(typetable.type,2) = type_translate.lookup