从WHERE IN删除,但有2个字段,没有Id

时间:2014-10-29 15:30:09

标签: sql sql-server delete-row sql-delete

我有这张桌子:

StudentId | ConfigurationTypeId
1         | 1
1         | 2
1         | 3
2         | 1
2         | 2

我想在ConfigurationTypeId = 3

时删除此表中的所有记录

所以我提出了这个问题:

DELETE FROM [StudentConfigurationType] WHERE StudentId IN
  (SELECT StudentId FROM [StudentConfigurationType] SCT 
  INNER JOIN [Student] S ON S.Id = SCT.StudentId
  WHERE SCT.ConfigurationTypeId = 3 AND S.RegisteredDate < '2014-09-18')

但是,因为这个表没有Id,所以StudentId进来了,它从表中删除了所有记录。 如何制作这样的东西:

DELETE FROM [StudentConfigurationType] WHERE StudentId AND ConfigurationTypeId IN
  (SELECT StudentId, ConfigurationTypeId FROM [StudentConfigurationType] SCT
  INNER JOIN [Student] S ON S.Id = SCT.StudentId
  WHERE SCT.ConfigurationTypeId = 3 AND S.RegisteredDate < '2014-09-18')

1 个答案:

答案 0 :(得分:5)

你可以试试这个:

DELETE FROM [StudentConfigurationType] WHERE (StudentId, ConfigurationTypeId) IN
  (SELECT StudentId, ConfigurationTypeId FROM [StudentConfigurationType] SCT
  INNER JOIN [Student] S ON S.Id = SCT.StudentId
  WHERE SCT.ConfigurationTypeId = 3 AND S.RegisteredDate < '2014-09-18');

或者这个:

DELETE FROM [StudentConfigurationType] 
WHERE StudentId IN (SELECT StudentId 
                      FROM [StudentConfigurationType] SCT
                           INNER JOIN [Student] S ON S.Id = SCT.StudentId
                      WHERE S.RegisteredDate < '2014-09-18')
 AND ConfigurationTypeId = 3;

或者这个:

DELETE FROM [StudentConfigurationType] st
WHERE EXISTS (SELECT 1 FROM [Student] S WHERE S.Id = ST.StudentId AND S.RegisteredDate < '2014-09-18')
 AND ConfigurationTypeId = 3;
相关问题