SQL Server:在几个表上使用LEFT OUTER JOIN条件的请求

时间:2016-08-26 08:20:05

标签: sql sql-server left-join

我想得到一个结果,其中包含有关在多个产品上执行的控制的信息,这些控件中包含的所有测量值,如果存在,则由控件控制的产品限制。

理想情况下,我想提出的要求是这样的:

SELECT c.ControlDate,
       m.Value,
       l.Upperlimit
FROM control c, measurement m
LEFT OUTER JOIN
LIMIT l
    ON l.ProductRef = c.ProductRef AND
       l.Spec = c.Spec AND
       l.CharacRef = m.CharacRef AND
       l.Active = 1
WHERE m.ControlRef = c.ControlRef 
...and many conditions concerning the m and the c tables

我知道我不能这样做:-) 但我无法找到有效的解决方案来获得结果。

我尝试了一个临时表(包含所有但我找不到解决方案以使其生效。 你有关于我应该这样做的建议吗?

1 个答案:

答案 0 :(得分:1)

简单规则:从不FROM子句中使用逗号。 始终使用显式JOIN语法,并使用ON子句中的条件。

我会从:

开始
select c.ControlDate, m.Value, l.Upperlimit
from control c left join
     measurement m
     on m.ControlRef = c.ControlRef left join
     limit l
     on l.ProductRef = c.ProductRef and
        l.Spec = c.Spec and
        l.CharacRef = m.CharacRef and
        l.Active = 1
where ...and many conditions concerning the m and the c tables

如果您想要所有控制日期,那么c表中的条件也应该包含在(适当的)on子句中。