使用delete sql语句嵌套select

时间:2013-05-08 21:09:48

标签: sql sql-server tsql inner-join

我不知道如何解决它:

我有一个选择声明:

SELECT 
       sum_lines.id, 
       sum_lines.line_id, 
       sum_lines.summary_id, 
       sum_lines.text_content, 
       sum_tbl.user_id 
FROM 
       sum_lines 
JOIN 
       sum_tbl 
ON 
       sum_lines.summary_id = sum_tbl.id 
WHERE 
       sum_tbl.user_id = 1 

如何删除此语句使用delete语句显示的所有内容?

2 个答案:

答案 0 :(得分:4)

如果要从两个表中删除,则需要两次删除:

delete sum_lines
from sum_lines
join sum_tbl on sum_lines.summary_id = sum_tbl.id where sum_tbl.user_id = 1

delete from sum_tbl 
where sum_tbl.user_id = 1

只需确保在删除内容之前进行备份。可以通过以下方式轻松完成:

select *
into sum_lines_backup
from sum_lines

select *
into sum_tbl_backup
from sum_tbl

答案 1 :(得分:0)

试试这个:

delete sum_lines from sum_lines as a

join sum_tbl as b on b.id = a.id 

where b.user_id = 1

确保列name sum_lines[id]数据必须与sum_tbl[id]匹配,否则无效。可能sum_lines.summary_id = sum_tbl.id与您数据库中的数据不匹配。