sql delete result from query

纵饮孤独 提交于 2019-12-08 13:50:06

问题


I have two tables, same structure

  • clients contains row 1+2
  • clients3 only row 2

I want to delete row 2 in the clients table

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

gives me the row 2. But I do not know how to delete.

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

does not work.


回答1:


You need to create temporary table for the subquery,

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



回答2:


No need to refer clients table twice in your query and remove * from DELETE clause -

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



回答3:


Try this

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


来源:https://stackoverflow.com/questions/12997586/sql-delete-result-from-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!