如何从sql中的左连接结果中删除重复记录

问题描述 投票:-2回答:1

我有三张桌子UserEnquiryActivity。当我做INNERLEFT JOIN时,由于NULL值,我得到重复记录。

用户:

User_id | user_firstName | user_lastName
--------+----------------+--------------
1       | Joe            | Smith 
2       | John           | Doe
3       | Robert         | Smith

查询:

EnquiryID  | CreatedBy|  
-----------+------------
1          |     1          
2          |     1           

活动:

ActivityID | CreatedBy| AssignedBy| AssignedTO
-----------+----------+-----------+----------- 
1          |     1    |    null   |  null      
2          |     1    |      2    |   3       

所有三个组合结果的预期输出是

Enquiry ID |  CreatedBy | AssignedBy | AssignedTO 
-----------+------------+------------+------------
1          |     Joe    |    null    |  null     
2          |     Joe    |      John  |   Rober  

SQL语句:

SELECT DISTINCT 
    E.EnquirdID AS Enquiry,
    U.FirstName AS CreatedBy,
    U1.FirstName AS AssignedBy,
    U2.FirstName AS AssignedTo
FROM 
    Enquiry E 
INNER JOIN 
    User U ON E.UserID = U.UserID 
INNER JOIN 
    Activity A ON E.Enquiry = A.EnquiryID
LEFT JOIN 
    User U1 ON A.AssignedBy = U1.UserID 
LEFT JOIN 
    User U2 ON A.AssignedTo = U2.UserID

我从这个查询得到重复的Enquiry记录,即使我使用DISTINCTEnquiryID

结果:我的计划是使用SQL来选择数据并在网站上以PHP显示它。这是一个查询管理网站。我希望能够让PHP从SQL中提取变量,所以我可以使用它们,但我认为合适。

sql duplicates left-join inner-join
1个回答
0
投票

查询似乎按预期工作。我刚刚修改了一些语法和列名:

SELECT DISTINCT E.EnquiryID as Enquiry, U.user_FirstName as CreatedBY ,U1.user_FirstName as AssignedBY  , U2.user_FirstName as AssignedTO 
FROM Enquiry E inner join [User] U on E.createdby = U.User_ID 
               inner join Activity A on E.EnquiryID = A.createdby
               Left Join [User] U1  on A.AssignedBY = U1.User_ID 
               Left Join [User] U2 on  A.AssignedTO = U2.User_ID
© www.soinside.com 2019 - 2024. All rights reserved.