【发布时间】:2016-04-03 18:55:37
【问题描述】:
我正在尝试像这样在 MySQL 中进行正确的连接:
SELECT customers.id,customers.firstname,customers.lastname,customers.email,orders.time,orders.notes,pendings.date_updated,pendings.issue,appointments.closed,appointments.job_description,backup_plans.expiration FROM customers
RIGHT JOIN orders
ON customers.id = orders.customer_id
ORDER BY orders.time DESC LIMIT 1
RIGHT JOIN pendings
ON customers.id = pendings.customer_id
ORDER BY pendings.date_updated DESC LIMIT 1
RIGHT JOIN appointments
ON customers.id = appointments.customer_id
ORDER BY appointments.closed DESC LIMIT 1
RIGHT JOIN backup_plans
ON customers.id = backup_plans.customer_id
ORDER BY backup_plans.expiration DESC LIMIT 1
我的意图是:选择客户的姓名和电子邮件,以及最近的订单、待处理、预约和备用计划探索。当我执行这个时,我得到一个语法错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RIGHT JOIN pendings
ON customers.id = pendings.customer_id
ORDER BY pendings.d' at line 5
我不熟悉联接,希望能提供任何帮助。
编辑 1:
似乎我需要按照 DanK 的建议进行子查询,如下所示:
SELECT customers.id,customers.firstname,customers.lastname,customers.email,orderstmp.time,orderstmp.notes FROM customers
RIGHT JOIN (
SELECT orders.time,orders.notes,orders.customer_id FROM orders ORDER BY orders.time DESC LIMIT 1
) as orderstmp ON orderstmp.customer_id = customers.id
但是当我这样做时,我只得到一行结果,而我想要所有客户信息。
编辑 2:
根据 Tom H 的建议,我构建了这个查询:
SELECT
customers.id,
SQ_O.time,
SQ_O.notes
FROM customers
LEFT JOIN (
SELECT
customers.id,
orders.time,
orders.notes
FROM customers
LEFT JOIN orders ON orders.customer_id = customers.id
ORDER BY orders.time DESC LIMIT 1
) AS SQ_O ON SQ_O.id = customers.id
其中包含所有空白时间和备注字段
和
SELECT
customers.id,
O1.time,
O1.notes
FROM customers
LEFT JOIN orders AS O1 ON O1.customer_id = O1.id
LEFT JOIN orders AS O2 ON O2.customer_id = customers.id AND O2.time > O1.time WHERE O2.customer_id IS NULL
达到最大执行时间。我猜这是因为与其他方言相比,我不熟悉 MySQL 中的可能性。
我也尝试过这样的相关子查询:
SELECT
customers.firstname,
customers.lastname,
customers.email,
(
SELECT CONCAT(orders.time,': ',orders.notes)
FROM orders
WHERE orders.customer_id = customers.id
ORDER BY orders.time DESC LIMIT 1
) as last_order
FROM customers
但“last_order”列出现空白。
最后,令人失望的编辑
在尝试了一些非常出色的建议后,这些建议帮助我显着地学习了 SQL,我决定编写一个 PHP 脚本来获得我想要的东西。该项目的最后期限有点过了,所以无论什么工作,工作。谢谢大家!
【问题讨论】:
-
每个查询只能有一个 ORDER BY 语句。
-
#1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 5 行的“RIGHT JOIN pendings ON customers.id = pendings.customer_id ORDER BY pendings.d”附近使用正确的语法
-
其他人几乎都涵盖了核心问题;但我想知道。为什么要加入
RIGHT?您是否期望有orders、pendings、appointments或backup_plans记录而没有关联客户记录? -
@Uueerdo 因为我是 n00b。感谢您的提示!
-
对于您的最新编辑,您需要在
email之后和(SELECT之前使用逗号;并且子查询不应该加入客户,它应该有一个WHERE orders.customer_id = customers.id(引用外部查询是使它“相关”的原因。
标签: mysql sql join sql-order-by