我有一个名为Team_table
的表,其中Team_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在所有表格中都可用 请建议我正确的解决方案
答案 0 :(得分: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
答案 1 :(得分:1)
一组right join
结束为空,最后一个表为空。如果第一个表为空,则一组left join
结束为空。但是一组full join
将返回任何匹配的行。因此,请考虑将right join
替换为full 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
答案 2 :(得分: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)