sql删除查询结果

时间:2012-10-21 11:57:43

标签: sql sql-server sql-delete

我有两张桌子,结构相同

  • clients包含第1 + 2行
  • clients3仅限第2行

我想删除clients

中的第2行
 SELECT * 
 FROM clients 
 WHERE EXISTS (SELECT * FROM clients3 WHERE clients3.id = clients.id))

给了我第2行。但我不知道如何删除。

DELETE * 
FROM clients 
WHERE (SELECT * 
       FROM clients 
       WHERE EXISTS (SELECT * FROM clients3 WHERE clients3.id = clients.id))

不起作用。

3 个答案:

答案 0 :(得分:2)

您需要为子查询创建临时表

DELETE 
FROM clients 
WHERE ID IN 
(
    SELECT ID
    FROM
    (
        SELECT ID FROM clients WHERE EXISTS (SELECT * FROM clients3 WHERE clients3.id = clients.id)
    ) x
)

答案 1 :(得分:1)

无需在查询中两次引用clients表格,并从*子句中删除DELETE -

DELETE c1
FROM clients c1
INNER JOIN clients3 c3 ON c3.id = c1.id --INNER JOIN will work as EXISTS for 1-1 Relation

答案 2 :(得分:0)

试试这个

   Delete from clients where id  in(select clients3.id from clients3)