左边连接子查询,只有一个结果

时间:2015-03-12 20:16:23

标签: sql tsql subquery left-join

这是一个查询:

SELECT 
k.[mg_KarId] AS [mg_KarId],
k.[SymKar] AS [SymKar],
k.[OpiKar] AS [OpiKar],
k.[Status] AS [Status],
kmlg.SymLok AS Lok_GLS1,
kmlk.SymLok AS Lok_KRS1,
kmlw.SymLok AS Lok_WLS1

FROM dbo.[mg_vv_Kar_All] AS k WITH (NOLOCK)

LEFT JOIN (
    SELECT kml.SymKar, kml.SymLok
    FROM dbo.mg_KarMagLok kml
    WHERE kml.Mag LIKE 'GLS1' 
    ) kmlg ON k.SymKar = kmlg.SymKar
LEFT JOIN (
    SELECT kml.SymKar, kml.SymLok
    FROM dbo.mg_KarMagLok kml
        WHERE kml.Mag LIKE 'KRS1'
        ) kmlk ON k.SymKar = kmlk.SymKar    
LEFT JOIN (
    SELECT kml.SymKar, kml.SymLok
    FROM dbo.mg_KarMagLok kml
        WHERE kml.Mag LIKE 'WLS1'
        ) kmlw ON k.SymKar = kmlw.SymKar
WHERE k.Status <> 'W'
and k.SymKar = '0006438';

它给我八行 - 每个LEFT JOIN(2 * 2 * 2)的两行:

2002111576  0006438 CUKIER  A   R03-C-05    S07-A-08    WR03-19-01
2002111576  0006438 CUKIER  A   R03-C-05    S07-A-08    WR04-20-50
2002111576  0006438 CUKIER  A   R03-C-05    S07-A-09    WR03-19-01
2002111576  0006438 CUKIER  A   R03-C-05    S07-A-09    WR04-20-50
2002111576  0006438 CUKIER  A   R04-A-02    S07-A-08    WR03-19-01
2002111576  0006438 CUKIER  A   R04-A-02    S07-A-08    WR04-20-50
2002111576  0006438 CUKIER  A   R04-A-02    S07-A-09    WR03-19-01
2002111576  0006438 CUKIER  A   R04-A-02    S07-A-09    WR04-20-50

我只需要一排 - 无论哪一排。我尝试将LEFT JOIN中的子查询修改为:

SELECT TOP 1 kml.SymKar, kml.SymLok
    FROM dbo.mg_KarMagLok kml
    WHERE kml.Mag LIKE 'GLS1'

但是它在Lok_GLS1列的主查询中给了我NULL。 我该如何解决这个问题?

4 个答案:

答案 0 :(得分:0)

这个子查询:

SELECT TOP 1 kml.SymKar, kml.SymLok
FROM dbo.mg_KarMagLok kml
WHERE kml.Mag LIKE 'GLS1'

TOP 1 dbo.mg_KarMagLok记录与<{1}}字段dbo.[mg_vv_Kar_All]相关,无关。因此,第一个SymKar很可能失败,导​​致LEFT JOIN(别名kmlg.SymLok)为Lok_GLS1

如果您想在子查询中使用NULL,则必须将TOP 1替换为LEFT JOIN

OUTER APPLY

答案 1 :(得分:0)

SELECT 
k.[mg_KarId] AS [mg_KarId],
k.[SymKar] AS [SymKar],
k.[OpiKar] AS [OpiKar],
k.[Status] AS [Status],
(
    SELECT TOP 1 kml.SymLok
    FROM dbo.mg_KarMagLok kml
    WHERE kml.Mag LIKE 'GLS1' 
    AND kml ON k.SymKar = kmlg.SymKar
) ,
(
    SELECT TOP 1 kml.SymLok
    FROM dbo.mg_KarMagLok kml
    WHERE kml.Mag LIKE 'KRS1'
    AND k.SymKar = kml.SymKar
) ,
(
    SELECT TOP 1 kml.SymLok
    FROM dbo.mg_KarMagLok kml
    WHERE kml.Mag LIKE 'WLS1'
    AND kmlw ON k.SymKar = kml.SymKar  
) 
FROM dbo.[mg_vv_Kar_All] AS k WITH (NOLOCK)
WHERE k.Status <> 'W'
and k.SymKar = '0006438';

您可以考虑使用子查询并避免3个连接

答案 2 :(得分:0)

如果您真的不关心结果集中的最后三列,为什么不这样做呢?

SELECT TOP 1
k.[mg_KarId] AS [mg_KarId],
k.[SymKar] AS [SymKar],
k.[OpiKar] AS [OpiKar],
k.[Status] AS [Status]

FROM dbo.[mg_vv_Kar_All] AS k WITH (NOLOCK)
WHERE k.Status <> 'W'
and k.SymKar = '0006438';

答案 3 :(得分:0)

如果要解决聚合问题,可以对数据集进行分组。 而不是使用TOP关键字,写一个这样的查询:

SELECT kml.SymKar, kml.SymLok
FROM dbo.mg_KarMagLok kml
WHERE kml.Mag LIKE 'GLS1'
group by kml.SymKar, kml.SymLok