用于删除查询的SQL

时间:2010-01-14 21:40:46

标签: mysql sql sql-delete

我正在尝试为我的程序编写SQL查询,但我无法弄清楚如何。我不太了解SQL。

我正在尝试实施在线团队系统(针对某些网站)。我有两张桌子:

teams | teamId, eventId
teammembers | teamId, userId, status

现在,我需要:删除teammembers中相应teamId的eventId为1的所有记录。

我正在尝试:

delete from teammembers where teamId=teams.teamId and teams.eventId=1;

我不确定这是否真的在做我想做的事情。

这个查询是错误的,如果是(可能是),我该如何编写这样的查询?

6 个答案:

答案 0 :(得分:12)

你没有指定你的RDBMS所以它在MySQL

DELETE teammembers FROM teammembers
JOIN teams on teammembers.teamId = teams.teamId
WHERE teams.eventId = 1

答案 1 :(得分:6)

这就是我在SQL Server中的做法

DELETE tm 
--select tm.*
FROM teammembers tm
JOIN teams t on tm.teamId = t.teamId 
WHERE t.eventId = 1 

通过在注释中嵌入一个select,我可以手动运行这个部分,看看在我开发过程中运行delete之前我将要影响的记录。

select tm.*
FROM teammembers tm
JOIN teams t on tm.teamId = t.teamId 
WHERE t.eventId = 1 

我没有第一次运行删除声明而没有检查我认为我要删除的记录是我打算删除的记录。此检查将使您更加担心更复杂的删除是否仅影响您想要影响的记录。

答案 2 :(得分:4)

您需要进行子查询或加入,我认为加入更快。

delete from teammembers
join teams on teammembers.teamid = teams.teamid
where teams.eventid = 1

答案 3 :(得分:3)

您需要使用multi-table delete syntax

DELETE teammembers
FROM teammembers
JOIN teams ON teamId=teams.teamId 
WHERE teams.eventId=1;

(我在这里假设MySQL)

答案 4 :(得分:1)

delete from teammembers where teamid in 
(
  select teamid from teams where eventid = 1
)

假设teamid是加入列。

答案 5 :(得分:0)

这就是你想要的:

delete from teammembers where teamId in (select teamId from teams where eventId=1);

编辑:正如一些评论已经提出的那样,更有效的方式确实是通过加入:

delete from teammebers
join teams on teams.teamId = teammembers.teamId
where eventId = 1