从别名连接构造中删除

时间:2013-10-28 10:59:36

标签: tsql join alias sql-delete

我想从连接构造中删除,我必须为其提供别名(“映射”),因为我还必须在连接中使用EXISTS子句。所以整个事情看起来像那样:

DELETE a
FROM (TableA a INNER JOIN 
        (SELECT * FROM TableX x INNER JOIN TableY y ON x.id = y.id) map
      ON a.key = map.key) mapped
WHERE EXISTS
      (SELECT * 
       FROM  LookUp l 
       WHERE l.key1 = mapped.TableAKey 
       AND   l.key2 = mapped.TableXKey
       AND   l.key3 = mapped.TableYKey)

问题似乎与括号有关,因为我收到错误:

Incorrect syntax near 'mapped'. 

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

我认为DELETE语句需要引用FROM子句中使用的别名。由于您的别名是“已映射”,请尝试按以下方式更改DELETE:

DELETE mapped
FROM (TableA a INNER JOIN 
        (SELECT * FROM TableX x INNER JOIN TableY y ON x.id = y.id) map
      ON a.key = map.key) mapped
WHERE EXISTS
      (SELECT * 
       FROM  LookUp l 
       WHERE l.key1 = mapped.TableAKey 
       AND   l.key2 = mapped.TableXKey
       AND   l.key3 = mapped.TableYKey)

答案 1 :(得分:0)

只需重写它,这样你就可以从显式表中删除并处理where子句中的所有条件。

DELETE TableA
WHERE
    EXISTS (
        SELECT * 
        FROM 
            TableX x 
            INNER JOIN TableY y ON x.id = y.id
        WHERE
            x.key = TableA.key and
            EXISTS (
                SELECT * 
                FROM  LookUp l 
                WHERE l.key1 = TableA.TableAKey 
                AND   l.key2 = x.TableXKey
                AND   l.key3 = y.TableYKey
            )
    )

另请注意,在您处理where子句时,将DELETE TableA替换为SELECT * FROM TableA可能会有所帮助,以确切了解哪些记录将被删除。