我有三张桌子User
,Enquiry
和Activity
。当我做INNER
和LEFT 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中提取变量,所以我可以使用它们,但我认为合适。
查询似乎按预期工作。我刚刚修改了一些语法和列名:
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