如何从SQL中进行左联接的结果中删除重复记录

时间:2019-03-09 16:34:19

标签: sql duplicates left-join inner-join

我有三个表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用于DISTINCT,我仍从此查询中获得重复的EnquiryID记录

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

1 个答案:

答案 0 :(得分: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