左外连接显示不正确的语法

时间:2015-08-19 19:48:11

标签: sql sql-server

我正在尝试做一个简单的左外连接。

内部查询工作正常。但是一旦我做了左外连接,我就会收到一条错误,说T1'附近的语法不正确并且' T2'附近的语法不正确。

我不知道我哪里错了。我是否包括一个我不应该在内部查询中的条件?

(SELECT * 
 FROM Table1 
 WHERE MMID IN 
       (SELECT MAX(MMID) 
        FROM Table1 
        WHERE (DateEntered) >= '2015-04-15 15:17:03.693'
        GROUP BY GID, MID)
) T1
LEFT OUTER JOIN
   (SELECT * 
    FROM Table1 
    WHERE (DateEntered) < '2015-04-15 15:17:03.693') T2 ON T1.GID = T2.GID AND T1.MID = T2.MID 
WHERE
    T1.Value <> T2.Value

2 个答案:

答案 0 :(得分:0)

如果这是您的实际查询,则缺少外部SELECT:

SELECT *
FROM (
    SELECT *
    FROM Table1
    WHERE MMID IN (
            SELECT MAX(MMID)
            FROM Table1
            WHERE (DateEntered) >= '2015-04-15 15:17:03.693'
            GROUP BY GID
                ,MID
            )
    ) T1
LEFT JOIN (
    SELECT *
    FROM Table1
    WHERE (DateEntered) < '2015-04-15 15:17:03.693'
    ) T2
    ON T1.GID = T2.GID
    AND T1.MID = T2.MID
WHERE T1.Value <> T2.Value

答案 1 :(得分:0)

语法应该归结为:

Select []
From A
Join B
on []

你的第一部分缺失了,因为你的第一个select实际上是T1子查询的一部分。在第一个括号之前添加另一个Select * from应解决语法问题。

或者,第一部分不需要是子查询:

SELECT * FROM Table1 T1
left outer join 
(
    Select * FROM Table1   
    where (DateEntered) < '2015-04-15 15:17:03.693'
) T2
    on T1.GID = T2.GID and T1.MID = T2.MID 
where T1.Value <> T2.Value
and T1.MMID IN 
(
    Select MAX(MMID) FROM Table1    
    where (DateEntered) >= '2015-04-15 15:17:03.693'
    group by GID, MID
)