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

Resultset not correct with JOIN between two table

我有这个问题。它有效但不正确。

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 table中没有像7这样的'ReasoneCode'的记录,我就没有收到任何记录。

如果在 table Linkup_Time 中该机器当天的 DurationInMinutes 列中没有值,我也想要结果。

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

这是因为您甚至在 WHERE 子句中过滤了来自 Linkup_Time table.

的列

试试这个:

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

当您使用 use l.ReasoneCode LIKE '%7%' 时,您的左联接被视为 INNER JOIN,因为它对于 Machine_Counter table.

为空

在 on join 的 ON 子句中添加此条件,而不是 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