我努力让这个SQL查询起作用。 我试图在一个查询中获取所需的信息,因为我得到的数据将使用PHP转换为CSV。
我的以下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,
PA.pay_Method
FROM Customers AS C
LEFT JOIN Tour AS T ON C.trip_Taken = T.tour_ID
LEFT JOIN Staff AS S ON O.staff_ID = S.staff_ID
LEFT JOIN Payment AS PA ON O.pay_ID = PA.pay_ID
WHERE 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 )
我收到此错误#1054 - Unknown column 'O.staff_ID' in 'on clause'
并且我不确定如何修复它。任何帮助将不胜感激。运行MySQL 5.0和最新的PHP
答案 0 :(得分:1)
你从其他答案得到错误的原因。如果您真的想加入Orders
,请在JOIN
下添加另一个Orders
条款,如下所示
FROM Customers AS C
LEFT JOIN Tour AS T ON C.trip_Taken = T.tour_ID
LEFT JOIN Orders AS OO ON C.customer_ID = OO.customer_ID <--Included
LEFT JOIN Staff AS S ON OO.staff_ID = S.staff_ID <-- Join with Orders
LEFT JOIN Payment AS PA ON OO.pay_ID = PA.pay_ID
答案 1 :(得分:0)
在某些时候你写了
LEFT JOIN Staff AS S ON O.staff_ID = S.staff_ID
但是&#34; O&#34;在括号范围内定义。在
中更改您的查询LEFT JOIN Staff AS S ON Orders.staff_ID = S.staff_ID
答案 2 :(得分:0)
报告的问题是由于O
别名是在子查询中引入的,因此无法在外部联接中使用。
考虑删除子查询,这也解决了初始问题。
SELECT ..
FROM Customers AS C
JOIN Orders AS O ON C.customer_ID = O.customer_ID -- Join/alias here
LEFT JOIN Tour AS T ON C.trip_Taken = T.tour_ID
LEFT JOIN Staff AS S ON O.staff_ID = S.staff_ID -- So it can be used here
LEFT JOIN Payment AS PA ON O.pay_ID = PA.pay_ID
-- Promote sub-query conditions
-- (FWIW, the conditions look odd: a customer has only one "travel date"?)
WHERE NOT (C.travel_Date >= '2014-07-08 00:00:00'
AND C.travel_Date <= '2014-07-08 23:59:59')
如果客户有 no 订单,则上述查询的行为会有所不同,可以通过根据意图将JOIN更改为LEFT JOIN来解决此问题。