SQL - 加入表和所有可能的结果

时间:2017-09-20 07:11:04

标签: sql sql-server

假设我有以下表格

SELECT C.Id, C.Color
FROM Color AS C

Id    Color
-------------------
 1    Strong Red
 2    Light Red
 3    Strong Blue
 4    Light Blue

SELECT L.Id, L.Place
FROM Location AS L

Id   Place
---------------
 1   Usa
 2   Japan

SELECT V.Id, V.PriceForADay, V.PriceForAWeek, V.ColorId, V.LocationId
FROM Vehicules AS V

Id   PriceForADay  PriceForAWeek ColorId  LocationId 
----------------------------------------------------
 1       10           15           1         1
 2       15           20           2         1
 3       20           25           1         2

我希望得到的结果是:

SELECT 
    C.Id, C.Color, V.PriceForADay, V.PriceForAWeek, V.ColorId,  
    V.LocationId/L.LocationId 
WHERE 
    V.LocationId = 1

Id  Color        PriceForADAy  PriceForAWeek  ColorId  LocationId
------------------------------------------------------------------
 1  Strong Red        10            20            1         1
 2  Light Red         15            25            2         1 
 3  Strong Blue       NULL          NULL          NULL      1
 4  Light Blue        NULL          NULL          NULL      1  

我怎样才能得到这个理想的结果?一个简单的左连接+哪里不起作用。

谢谢

3 个答案:

答案 0 :(得分:1)

根据您的结果,强蓝和浅蓝位于位置1。 但是,提供的数据集在位置1中没有这些颜色。 同样对于c.Id(ColorId)2,3结果,相应的ColorId在结果中为空,我猜这是错误的。因此,以下查询仅基于猜测的数据集: -

DECLARE @Color TABLE (Id INT IDENTITY (1,1) PRIMARY KEY, Color VARCHAR(30))
INSERT INTO @Color (Color) VALUES('Strong Red'), ('Light Red'),('Strong Blue'),('Light Blue')

DECLARE @Location TABLE (Id INT IDENTITY (1,1) PRIMARY KEY, Place VARCHAR(30))
INSERT INTO @Location (Place) VALUES('USA'), ('Japan')

DECLARE @Vehicules TABLE (Id INT IDENTITY (1,1) PRIMARY KEY, PriceForADay INT, PriceForAWeek INT,
     ColorId INT, LocationId INT)
INSERT INTO @Vehicules(PriceForADay, PriceForAWeek, ColorId, LocationId) VALUES(10,15,1,1),(15,20,2,1),(20,25,1,2)
,(NULL,NULL,3,1),(NULL,NULL,4,1)

--SELECT * FROM @Color
--SELECT * FROM @Location
--SELECT * FROM @Vehicules 

SELECT
    C.Id, C.Color, V.PriceForADay, V.PriceForAWeek, V.ColorId
    ,L.Id AS LocationID
FROM  @Color C LEFT JOIN @Vehicules V ON C.Id = V.ColorId
LEFT JOIN @Location L ON V.LocationId = L.Id
WHERE V.LocationId = 1

答案 1 :(得分:0)

写一个OUTER APPLY

SELECT C.Id,C.Color,V.PriceForADay,V.PriceForAWeek,V.ColorId,  V.LocationId/L.LocationId 
FROM Vehicules AS V 
OUTER APPLY Color AS C
where V.LocationId = 1

在这里阅读更多内容:

http://sqlhints.com/tag/outer-apply-examples/

答案 2 :(得分:0)

这应该做的工作:

select C.Id, C.Color, V.PriceForADAy, V.PriceForAWeek, V.ColorId, L.Id
from Colors AS C left join Vehicules AS V on C.Id = V.ColorId
join Location AS L on V.LocationId = L.Id
where L.Id = 1