您好我有以下SQL查询,它提供了 ProjectSchemes 和 Schemes 表中存在的 Scheme_Id 。我想删除 Schemes 表中没有 ProjectSchemes 表记录的所有记录。我怎么能这样做?请帮忙。我正在使用MSSQL
select scheme_id from Schemes where Scheme_Id
in(select s.Scheme_Id from Projects p
inner join ProjectSchemes ps on ps.Project_Id=p.Project_Id
inner join Schemes s on s.Scheme_Id=ps.Scheme_Id)
我试图执行以下操作,但它无法正常工作。不工作意味着没有受影响的记录但是当我检查我的Schemes表时,有太多的记录表明他们的scheme_id在ProjectSchemes表上找不到
delete from Schemes where Scheme_Id
not in(select s.Scheme_Id from Projects p
inner join ProjectSchemes ps on ps.Project_Id=p.Project_Id
inner join Schemes s on s.Scheme_Id=ps.Scheme_Id)
答案 0 :(得分:9)
DELETE FROM schemes
WHERE scheme_id NOT IN (
SELECT DISTINCT scheme_id
FROM projectschemes
WHERE scheme_id IS NOT NULL
)
或者您也可以使用
DELETE
FROM schemes
WHERE NOT EXISTS (
SELECT 1
FROM projectschemes
WHERE projectschemes.scheme_id = schemes.ID
)
答案 1 :(得分:8)
我想从假设开始。
因此,SELECT会列出Schemes表中所有Schemes的scheme_id。
说,你应该开始删除没有相应项目的所有ProjectSchemes。这些是ProjectSchemes,其id为NULL或项目表中不存在的id:
DELETE ProjectSchemes WHERE (Project_Id is NULL) OR
(NOT EXISTS (SELECT * FROM Projects WHERE
Projects.Project_Id = ProjectSchemes.Project_Id))
在没有Project的情况下删除ProjectsSchemes后,我们现在可能在Schemes Table中有一些新的孤儿。接下来要删除所有ID为NULL或在ProjectsSchemes表中不存在的ID的方案:
DELETE Schemes WHERE (Scheme_Id is NULL) OR
(NOT EXISTS (SELECT * FROM ProjectSchemes WHERE
ProjectSchemes.Scheme_Id = Schemes.Scheme_Id))
在没有删除ProjectSchemes的情况下,仍有机会将项目与项目无关。
答案 2 :(得分:3)
DELETE s
FROM Schemes s LEFT JOIN ProjectSchemes ps ON s.Scheme_Id=ps.Scheme_Id
WHERE ps.Scheme_Id IS NULL
但听起来你需要这个
DELETE sp
FROM ProjectSchemes sp LEFT JOIN Schemes s ON sp.Scheme_Id=s.Scheme_Id
WHERE s.Scheme_Id IS NULL