我正在尝试编写一个sql查询来查询涉及联结表的多个表中的记录。 Userprofile表与Role和team table有关系,与TimeZone表有一对一的关系。
我正在尝试实现一个查询,该查询将从UserProfile表中提取记录以及来自Role,team和timezone表的相关记录。我试图写一个查询,它变得过于复杂。有人可以验证我的查询并告诉我正确的方法吗
表格如下
UserProfile表
[EmployeeID]
[Forename]
[Surname]
[PreferredName]
[DefaultLanguageCode]
[DefaultCountryCode]
[TimeZoneID]
[Domain]
[NetworkID]
团队表
[TeamID]
[CountryCode]
[TeamName]
[TeamDescription]
UserTeamLinkTable
[UserProfileTeamLinkID]
[TeamID]
[UserProfileID]
[isDefault]
[isActive]
UserRole表
[RoleID]
[RoleDescription]
[isActive]
UserRoleLink表
[UserProfileRoleLinkID]
[RoleID]
[UserProfileID]
[isActive]
TimeZone表
[TimeZoneID]
[TimeZoneCode]
[TimeZone]
[TimeZoneName]
查询
select
userprofile.[UserProfileID]
,userprofile.[EmployeeID]
,userprofile.[Forename]
,userprofile.[Surname]
,userprofile.[PreferredName]
,userprofile.[DefaultCountryCode]
,userprofile.[DefaultLanguageCode]
,userprofile.[TimeZoneID]
,userprofile.TeamID
,userprofile.TeamName
,userprofile.[Domain]
,userprofile.[NetworkID]
,userprofile.[EmailAddress]
,userprofile.[CreatedDate]
,userprofile.[CreatedBy]
,userprofile.[ModifiedDate]
,userprofile.[ModifiedBy]
from TimeZone tz inner join
(
select
up.[UserProfileID]
,up.[EmployeeID]
,up.[Forename]
,up.[Surname]
,up.[PreferredName]
,up.[DefaultCountryCode]
,up.[DefaultLanguageCode]
,up.[TimeZoneID]
,te.TeamID
,te.TeamName
,up.[Domain]
,up.[NetworkID]
,up.[EmailAddress]
,up.[CreatedDate]
,up.[CreatedBy]
,up.[ModifiedDate]
,up.[ModifiedBy]
from [dbo].[UserProfileTeamLink] upt
inner join UserProfile up on up.UserProfileID = upt.UserProfileID
inner join Team te on te.TeamID = upt.TeamID ) userprofile on tz.TimeZoneID = userprofile.TimeZoneID
答案 0 :(得分:0)
很难说不知道数据是什么样的或者想要的输出是什么样的。如果由于多对多关系而期望每个用户有多行,则可以在不使用子查询的情况下加入所有表。
select
up.[UserProfileID]
,up.[EmployeeID]
,up.[Forename]
,up.[Surname]
,up.[PreferredName]
,up.[DefaultCountryCode]
,up.[DefaultLanguageCode]
,up.[TimeZoneID]
,tz.TimeZone
,te.TeamID
,te.TeamName
,up.[Domain]
,up.[NetworkID]
,up.[EmailAddress]
,up.[CreatedDate]
,up.[CreatedBy]
,up.[ModifiedDate]
,up.[ModifiedBy]
,ur.RoleDescription
from UserProfile up
inner join TimeZone tz
on tz.TimeZoneID = up.TimeZoneID
inner join UserProfileTeamLink upt
on upt.UserProfileID = upt.UserProfileID
--and upt.isDefault = 1 /* default team only? */
--and upt.isActive = 1 /* active team only? */
inner join Team te
on te.TeamID = upt.TeamID
inner join UserProfileRoleLink upr /* left join if users might not have a role*/
on up.UserProfileID = upr.UserProfileId
--and upr.isActive = 1 /* active role only? */
inner join UserRole ur /* left join if users might not have a role*/
on upr.RoleId = ur.RoleId