我正在使用DB2,如果数据库中没有存在IN子句中存在的ID的行,我想要返回虚拟值
SELECT A.EmpName, A.EmpId,B.Address, C.OrgCode
FROM Employee A
join Address B on A.EmpId = B.EmpId
join Organization C on A.EmpId = C.EmpId
where A.SecretId in ('1', '2', '3', '4', '5');
我在数据库中使用Secret Id 1,2,3,4的员工但不是5但我需要的结果如下所示
EmpId EmpName Address OrgCode
1 A XXX 23
2 B YYY 44
3 C ZZZZ 21
4 D KKK 23
5 N/A N/A N/A
我需要用一些虚拟值填充值。我从其他系统获取秘密ID列表。
请帮助我实现这一目标。
我使用DB2作为我的数据库。
答案 0 :(得分:1)
您需要一个left join
,并从您没有的价值开始:
SELECT e.EmpName, el.EmpId, a.Address, o.OrgCode
FROM (SELECT 1 as EmpId FROM sysibm.sysdummy1 UNION ALL
SELECT 2 as EmpId FROM sysibm.sysdummy1 UNION ALL
SELECT 3 as EmpId FROM sysibm.sysdummy1 UNION ALL
SELECT 4 as EmpId FROM sysibm.sysdummy1 UNION ALL
SELECT 5 as EmpId FROM sysibm.sysdummy1
) el LEFT JOIN
Employee e
ON el.EmpId = e.EmpId LEFT JOIN
Address a
ON el.EmpId = a.EmpId LEFT JOIN
Organization o
ON el.EmpId = o.EmpId ;
或使用方便的快捷方式:
SELECT e.EmpName, el.EmpId, a.Address, o.OrgCode
FROM (VALUES (1), (2), (3), (4), (5)) el(EmpId)
Employee e
ON el.EmpId = e.EmpId LEFT JOIN
Address a
ON el.EmpId = a.EmpId LEFT JOIN
Organization o
ON el.EmpId = o.EmpId ;
答案 1 :(得分:1)
通过更新,它仍然是左连接:
SELECT t.EmpId, NVL(A.EmpName, 'N/A'), NVL(B.Address, 'N/A'),
NVL(C.OrgCode, 'N/A')
FROM TABLE(VALUES ('1'), ('2'), ('3'), ('4'), ('5')) AS t(empid)
LEFT OUTER JOIN Employee A
ON t.empid = A.empid
LEFT OUTER JOIN Address B
ON t.EmpId = B.EmpId
LEFT OUTER JOIN Organization C
ON t.EmpId = C.EmpId
;
作为一个注释,通过将数字放在引号中,您将它们变成一个字符串。如果EmpId是一个字符串,这很好,但如果它是一个数字,那么它的效率会降低。
答案 2 :(得分:0)
尝试使用LEFT JOIN
代替:
SELECT A.EmpName, A.EmpId,B.Address, C.OrgCode
FROM Employee A
left join Address B on A.EmpId = B.EmpId
left join Organization C on A.EmpId = C.EmpId
where A.EmpId in ('1', '2', '3', '4', '5');