SQL查询不会连接我的结果

时间:2014-07-31 00:57:39

标签: php mysql sql sql-server

我一直在阅读一些文章,但却无法掌握SQL。我有这个SQL查询:

SELECT C.customer_ID, C.l_Name AS Surname, 
C.f_Name AS 'First Name', C.travel_Date,
T.tour_Name, 
S.f_Name AS Staff, S.l_Name AS Staff_Surname
FROM Customers AS C 
LEFT JOIN Tour AS T ON C.tour_ID = T.tour_ID
LEFT JOIN Staff_Day AS SD ON C.tour_ID = SD.tour_ID
LEFT JOIN Staff AS S ON SD.staff_ID = S.staff_ID
LEFT JOIN Staff_Day AS SD_2 ON SD_2.sd_Date = C.travel_Date 
WHERE  C.travel_Date >= '2014-07-08 00:00:00' 
AND C.travel_Date <= '2014-07-08 23:59:59'
AND SD.sd_Date >= '2014-07-08 00:00:00' 
AND SD.sd_Date <= '2014-07-08 23:59:59'
AND C.customer_ID NOT IN (SELECT O.customer_ID 
FROM Customers AS C, Orders AS O 
WHERE C.travel_Date >= '2014-07-08 00:00:00' 
AND C.travel_Date <= '2014-07-08 23:59:59' AND C.customer_ID = O.customer_ID )

返回4个结果:

6176    Lau Elton   2014-07-08 09:07:33 Thriller        Jo(Boat)
6176    Lau Elton   2014-07-08 09:07:33 Thriller        Gosta   (the boss man)
6192    minc yvonne 2014-07-08 09:07:47 Thunderstruck   Jo(Jetty)
6192    minc yvonne 2014-07-08 09:07:47 Thunderstruck   Meri    (Jetty)

我真的难以理解如何将4个结果合并为2.如果有帮助,每个客户(Lau,Minc)都有2名工作人员,我相信这是2个额外返回结果的原因。我尝试过GROUP_CONCAT,但我不太了解它以使其正常工作。我希望结果如此:

6176    Lau Elton   2014-07-08 09:07:33 Thriller        Jo(Boat), Gosta (the boss man)
6192    minc yvonne 2014-07-08 09:07:47 Thunderstruck   Jo(Jetty), Meri (Jetty)

这一切都可能吗?如果这已经重复,请道歉。

1 个答案:

答案 0 :(得分:1)

感谢@Michael Haugen指出我正确的方向,我能够修改现有的SQL查询以返回预期的结果:

SELECT C.customer_ID, C.l_Name AS Surname, 
C.f_Name AS 'First Name', C.travel_Date,
T.tour_Name, 
GROUP_CONCAT(S.f_Name, S.l_Name ) AS Staff_Concat
FROM Customers AS C 
LEFT JOIN Tour AS T ON C.tour_ID = T.tour_ID
LEFT JOIN Staff_Day AS SD ON C.tour_ID = SD.tour_ID
LEFT JOIN Staff AS S ON SD.staff_ID = S.staff_ID
LEFT JOIN Staff_Day AS SD_2 ON SD_2.sd_Date = C.travel_Date 
WHERE  C.travel_Date >= '2014-07-08 00:00:00' 
AND C.travel_Date <= '2014-07-08 23:59:59'
AND SD.sd_Date >= '2014-07-08 00:00:00' 
AND SD.sd_Date <= '2014-07-08 23:59:59'
AND C.customer_ID NOT IN (SELECT O.customer_ID 
FROM Customers AS C, Orders AS O 
WHERE C.travel_Date >= '2014-07-08 00:00:00' 
AND C.travel_Date <= '2014-07-08 23:59:59' AND C.customer_ID = O.customer_ID )
GROUP BY C.customer_ID