我有这张桌子:
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')
答案 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;