2016-11-10 51 views
0

我有以下列tblProject dataTable中重複的記錄問題:與獲得使用連接在SQL Server

ID, 
Title, 
Estimator, 
ConstructionCoordinator, 
ConstructionManager, 
EnteredBy, 
AssignedTo, 
ProjectCoordinator, 
SalesLead 

上述所有的列沒有前兩個是tblUser用戶ID數據表的條目,如下所示

UserId, 
UserName 

我想從tblProject中獲得所有記錄(其中沒有前兩個即ID和標題)包含UserId of tblUser

我嘗試下面的查詢,

select * from Project PRJ 
inner join UserProfile UP on UP.UserId = PRJ.Estimator or UP.UserId = PRJ.ConstructionCoordinator 
        or UP.UserId = PRJ.ConstructionManager or UP.UserId = PRJ.EnteredBy or UP.UserId = PRJ.AssignedTo 
        or UP.UserId = PRJ.ProjectCoordinator or UP.UserId = PRJ.SalesLead 

但我得到重複的記錄,在ID and Title列如何讓不同的數據?

由於基於

回答

0

定勢思維,其中intersect類似於邏輯ANDunion類似於邏輯OR,使我這個:

select UserId from UserProfile 
intersect 
(select Estimator from Project 
    union 
    select ConstructionCoordinator from Project 
    union 
    select ConstructionManager from Project 
    union 
    select EnteredBy from Project 
    union 
    select AssignedTo from Project 
    union 
    select ProjectCoordinator from Project 
    union 
    select SalesLead from Project); 

要返回所有列,按照你的SQL,你可以:

select * from Project where UserId in 
(select Estimator from Project 
    union 
    select ConstructionCoordinator from Project 
    union 
    select ConstructionManager from Project 
    union 
    select EnteredBy from Project 
    union 
    select AssignedTo from Project 
    union 
    select ProjectCoordinator from Project 
    union 
    select SalesLead from Project);