当结果值基于主表中存在匹配时,Left Outer Join不返回所有行

时间:2014-01-21 19:48:22

标签: sql join isnull

LEFT JOIN未返回结果中的所有行。结果基于主表中相应值的存在。例如,Break(主要)和Event(辅助)表。如果两者中都存在查找值,则返回Event表中的值。如果该值仅存在于Break表中,则返回Break值。但是,如果需要,当Event值不存在时,返回Break值并将Event值设置为零/ NULL也是可以接受的。我把查询缩减到这个部分,因为我已经进行了广泛的研究而无法得到准确的结果。非常感谢任何帮助。

SELECT DISTINCT
    ISNULL (e.breaktime, b.breaktime)
FROM
    Break b
LEFT JOIN  Event e (nolock)
    ON  e.breakdate = b.breakdate 
    and e.breaktime = b.breaktime
WHERE
    b.breaktime between 18000 and 86400
GROUP BY b.breaktime, e.breaktime
ORDER BY b.breaktime 

2 个答案:

答案 0 :(得分:0)

将条件移至JOIN

SELECT DISTINCT ISNULL(e.breaktime, b.breaktime) AS breaktime
  FROM Break b
       LEFT JOIN Event e (NOLOCK)
    ON e.breakdate = b.breakdate 
   AND e.breaktime = b.breaktime
   AND b.breaktime BETWEEN 18000 AND 86400
 GROUP BY b.breaktime, e.breaktime 
 ORDER BY breaktime

答案 1 :(得分:0)

我认为您遇到的问题是您将左表指定为“事件”。我想你想发表声明:

SELECT DISTINCT ISNULL (e.breaktime, b.breaktime) 
FROM Break b 
LEFT JOIN Event e (nolock) 
ON 
     b.breakdate = e.breakdate
     and b.breaktime = e.breaktime
WHERE 
     b.breaktime between 18000 and 86400 
GROUP BY b.breaktime, e.breaktime
ORDER BY b.breaktime