左连接两个表并将未映射的值取为未知

时间:2014-09-26 16:18:26

标签: sql sql-server

我有两张桌子:

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

1 个答案:

答案 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

SQL Fiddle

结果是:

╔═══════╦═════════╦═════════╦═══════════╗
║ MapId ║ MapName ║ IndexId ║ IndexName ║
╠═══════╬═════════╬═════════╬═══════════╣
║     1 ║ M1      ║       1 ║ A         ║
║     2 ║ M2      ║       2 ║ B         ║
║    -1 ║ Unknown ║       3 ║ C         ║
╚═══════╩═════════╩═════════╩═══════════╝