2016-04-12 167 views
0

我现在有两个表存储数据。它们通过ID值相关联。我如何返回表1中的所有值,包括主值,即使匹配。这是我的基本查询。左连接返回连接值

Select MFG.mfgname, SS.subsysname 
From Manufacturers MFG left join SubSystem SS 
On MFG.id = SS.mfgid 
Order by MFG.mfgname, SS.subsysname 

下面是表

MFG Table  
id mfgname 
1 ABB 
2 Siemens 
3 Vipa  
4 Visolux 

SubSystem table  
id mfgid subsysname 
1 1 ABB Drives 
2 1 ABB Robots 
3 1 Advant OCS 
4 2 Simatic S5 
5 2 Simatic S7 
6 3 Vipa System 

最后的结果和预期的结果。

Results 
mfgname subsysname 
ABB ABB Drives 
ABB ABB Robots 
ABB Advant OCS 
Siemens Simatic S5 
Siemens Simatic S7 
Vipa Vipa System 
Visolux NULL 

Desired Results 
mfgname subsysname 
ABB NULL 
ABB ABB Drives 
ABB ABB Robots 
ABB Advant OCS 
Siemens NULL 
Siemens Simatic S5 
Siemens Simatic S7 
Vipa NULL 
Vipa Vipa System 
Visolux NULL 

期望的结果还会返回带有空子系统名称的ABB,西门子和Vipa mfgs。此时它没有。希望这是有道理的!

回答

2

你应该可以使用UNION来做到这一点。

SELECT MFG.mfgname, 
     SS.subsysname 
FROM Manufacturers MFG 
     LEFT JOIN SubSystem SS ON MFG.id = SS.mfgid 
UNION 
SELECT MFG.mfgname, 
     NULL 
FROM Manufacturers MFG 
ORDER BY MFG.mfgname, 
     SS.subsysname 
+1

如果将'left join'更改为'inner join'并将'union'更改为'union all',可以避免需要独特的排序? –

+2

如果'subsysname'不能为空,你可以使用inner join和union all – JamieD77