两个表之间的JOIN结果集不正确

时间:2015-01-09 10:05:20

标签: sql left-join inner-join

我有这个查询。它工作但不正确。

SELECT 
    mc.Quantity as Production,
    mc.Data as Date,
    mc.Machine as Equipment,
    mc.DesignSpeed,
    k.Value,
    SUM(l.DurationInMinutes)/60 as DurationInMinutes
FROM
    Machine_Counter mc INNER JOIN 
    Linkup_Time l ON (mc.Data = l.ProductionDate AND mc.Machine = l.Machine) INNER JOIN 
    KPI_Value k ON (mc.Data = k.Data AND mc.Machine = k.Machine) 
WHERE 
    mc.CounterType = 1 AND 
    mc.Machine LIKE @MACHINE AND
    k.KPI = 3 AND
    mc.Data BETWEEN @DATA_START AND @DATA_END AND
    l.ReasoneCode LIKE '%7%'
GROUP BY
    mc.Quantity,
    mc.Data,
    mc.Machine,
    mc.DesignSpeed,
    k.Value
ORDER BY mc.Data

问题在于第一次INNER JOIN

Machine_Counter mc INNER JOIN 
        Linkup_Time l ON (mc.Data = l.ProductionDate AND mc.Machine = l.Machine)

因为如果在Linkup_Time表中没有任何带有' ReasoneCode'的记录。像7,我没有收到任何记录。

如果在表Linkup_Time中,那台机器当天的那段时间内没有一个值,那么我也想要结果。

我尝试使用LEFT JOIN但结果是一样的。

2 个答案:

答案 0 :(得分:1)

使用l.ReasoneCode LIKE '%7%'时,左连接被视为INNER JOIN,因为Machine_Counter表为空。

ON子句中为on join而不是where子句添加此条件。

SELECT 
    mc.Quantity as Production,
    mc.Data as Date,
    mc.Machine as Equipment,
    mc.DesignSpeed,
    k.Value,
    SUM(l.DurationInMinutes)/60 as DurationInMinutes
FROM  Machine_Counter mc 
LEFT JOIN  Linkup_Time l ON (mc.Data = l.ProductionDate 
                        AND  mc.Machine = l.Machine
                        AND  l.ReasoneCode LIKE '%7%') 
INNER JOIN 
    KPI_Value k ON (mc.Data = k.Data AND mc.Machine = k.Machine
                AND k.KPI = 3 ) 
WHERE mc.CounterType = 1
  AND mc.Machine LIKE @MACHINE 
  AND mc.Data BETWEEN @DATA_START AND @DATA_END 
     GROUP BY
        mc.Quantity,
        mc.Data,
        mc.Machine,
        mc.DesignSpeed,
        k.Value
    ORDER BY mc.Data

答案 1 :(得分:0)

这是因为您甚至在WHERE子句中过滤了Linkup_Time表中的一列。

试试这个:

SELECT mc.Quantity as Production
      ,mc.Data as Date
      ,mc.Machine as Equipment
      ,mc.DesignSpeed
      ,k.Value
      ,SUM(l.DurationInMinutes)/60 as DurationInMinutes
FROM Machine_Counter mc
LEFT JOIN Linkup_Time l 
    ON (mc.Data = l.ProductionDate AND mc.Machine = l.Machine) 
INNER JOIN KPI_Value k 
    ON (mc.Data = k.Data AND mc.Machine = k.Machine) 
WHERE mc.CounterType = 1 
  AND mc.Machine LIKE @MACHINE 
  AND k.KPI = 3 
  AND mc.Data BETWEEN @DATA_START AND @DATA_END
  AND (l.ReasoneCode LIKE '%7%' OR l.ReasoneCode IS NULL)
GROUP BY mc.Quantity
        ,mc.Data
        ,mc.Machine
        ,mc.DesignSpeed
        ,k.Value
ORDER BY mc.Data