我有两张桌子:
Table1
IndexId IndexName
1 A
2 B
3 C
Table2
MapId MapName MapIndexId
1 M1 1
2 M2 2
我想基于Table2.MapIndexId = Table1.IndexId连接两个表并获得结果
MapId MapName IndexId IndexName
1 M1 1 A
2 M2 2 B
-1 Unknown 3 C
答案 0 :(得分:4)
SELECT ISNULL(T2.MapId,-1) MapId,
ISNULL(T2.MapName,'Unknown') MapName,
T1.IndexId,
T1.IndexName
FROM Table1 T1
LEFT JOIN Table2 T2
ON T1.IndexId = T2.MapIndexId
结果是:
╔═══════╦═════════╦═════════╦═══════════╗
║ MapId ║ MapName ║ IndexId ║ IndexName ║
╠═══════╬═════════╬═════════╬═══════════╣
║ 1 ║ M1 ║ 1 ║ A ║
║ 2 ║ M2 ║ 2 ║ B ║
║ -1 ║ Unknown ║ 3 ║ C ║
╚═══════╩═════════╩═════════╩═══════════╝