请帮我解决我想写的sql查询

时间:2014-05-20 08:11:12

标签: mysql sql sql-delete

我想从其父级为CTSC的所有compartmentID中删除IITESE。但我得到了这个错误说

  

Msg 512,Level 16,State 1,Line 3   子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我的查询是

delete  from [KRISADMIN].[CompartmentACL] where CompartmentID = (select CompartmentID from [KRISADMIN].[Compartment] where Name = 'CTSC') and 
TrusteeID = (select RoleID from [KRISADMIN].[Role] where Name = 'IITSE') and TrusteeType = 2

如果不好,请原谅我的询问。

1 个答案:

答案 0 :(得分:2)

当子查询只返回1个值时,可以使用=。

当子查询返回的值超过1时,您必须使用INEXISTS

使用IN

delete  from [KRISADMIN].[CompartmentACL] 
where CompartmentID IN (select CompartmentID 
                        from [KRISADMIN].[Compartment] 
                        where Name = 'CTSC') 
and TrusteeID IN (select RoleID 
                  from [KRISADMIN].[Role] 
                  where Name = 'IITSE') 
and TrusteeType = 2

了解更多here

修改

您需要将=替换为IN

delete from [KRISADMIN].[CompartmentACL] 
where CompartmentID IN (select CompartmentID 
                        from [KRISADMIN].[Compartment] 
                        where Name in (Select Name 
                                       from [KRISADMIN].[Compartment] 
                                       where ParentID IN (Select ParentID 
                                                         from [KRISADMIN].[Compartment] 
                                                         where Name = 'CTSC') )) 
and TrusteeID IN (select RoleID 
                  from [KRISADMIN].[Role] 
                  where Name = 'IITSE') 
and TrusteeType = 2