0

我有一个名为以Team_tableTeam_Id作为主键的表,并且 4 个不同的表是Team_Member, Team_Project, Team_Account,Team_link也包含这个Team_Id

在从 中删除一个团队之前Team_table,我必须在所有 4 个表中检查它的引用。如果Team_Id在任何一个表中找到它,用户不能删除它。

我做了以下查询,但它不工作-

select count(Team.Team_Id)
  from Team 
  join Team_Project on Team.Team_Id = Team_Project.Team_Id  
 right join Team_Member on Team.Team_Id = Team_member.Team_Id  
 right join Team_link on Team.Team_Id = Team_link.Team_Id  
 right join Team_Account on Team.Team_Id = Team_Account.Team_Id  
 where Team.Team_Id = 2

但它总是给我 0,而这个 team_Id 在所有表中都可用。
请建议我正确的解决方案

4

3 回答 3

1

试试这个:

declare @teamid int=2;

Select Team_Id from Team_Project where Team_Id=@teamid union all
Select Team_Id from Team_Member  where Team_Id=@teamid union all
Select Team_Id from Team_link    where Team_Id=@teamid union all
Select Team_Id from Team_Account where Team_Id=@teamid; 

if @@ROW_COUNT=0 delete from TEAM where Team_Id=@teamid
于 2012-09-17T06:49:43.180 回答
1

一组right join最终是空的,最后一个表是空的。如果第一个表为空,则一组left join最终为空。但是一组full join将返回任何匹配的行。所以考虑right joinfull join.

not exists作为另一种选择,我发现使用子句而不是join这种查询更清楚:

delete  t
from    Team t
where   t.Team_Id = @TeamId
        and not exists (select * from Team_Project where Team_Id = @TeamId)
        and not exists (select * from Team_Member where Team_Id = @TeamId)
        and not exists (select * from Team_link where Team_Id = @TeamId)
        and not exists (select * from Team_Account where Team_Id = @TeamId)

根据您的评论,检索计数:

select  count(*)
from    (
        select  Team_Id 
        from    Team_Project 
        union all
        select  Team_Id 
        from    Team_Member  
        union all
        select  Team_Id 
        from    Team_link    
        union all
        select  Team_Id 
        from    Team_Account 
        ) as SubQueryAlias
where   Team_Id = @TeamId
于 2012-09-17T06:56:35.233 回答
0
select count(Team.Team_Id) 
from Team 
left join Team_Project 
   on Team.Team_Id=Team_Project.Team_Id  
left join Team_Member 
   on Team.Team_Id=Team_member.Team_Id  
left join Team_link 
   on Team.Team_Id=Team_link.Team_Id  
left join Team_Account 
   on Team.Team_Id= Team_Account.Team_Id  
where Team.Team_Id=2 and 
(Team_Project.Team_Id is not null
 of 
 Team_member.Team_Id is not null
 or 
 Team_link.Team_Id is not null
 or
 Team_Account.Team_Id is not null)
于 2012-09-17T06:50:08.273 回答