在MySQL中具有以下数据库结构:
表1:订购 具有属性
表2:客户 具有属性
表3:餐厅
我想生成一个数据库查询,在其中选择customer_ID,login,Delivery_date,序列号以及从最后一个订单到倒数第二个订单的天数。
我在使用内部联接并生成查询的最后两列时遇到麻烦:
到目前为止,我已经构造了以下查询:
SELECT customer_id,
login,
delivery_date,
sequence,
Datediff(second_to_last_order, last_order)
FROM order AS t1
INNER JOIN customer AS t2
ON t1.customer_id = t2.id
INNER JOIN restaurant AS t3
ON t1.restaurant_id = t3.id;
但这显然是不完整的,但是我被卡住了,有什么建议吗?
答案 0 :(得分:0)
如果这是您提到的MySQL Server查询,那么我建议您进行以下操作;
SELECT CUSTOMER_ID, LOGIN, DELIVERY_DATE, SEQUENCE, DATEDIFF((SELECT MAX(z.ORDER_DATE) FROM ORDER AS z WHERE z.CUSTOMER_ID = t1.CUSTOMER_ID), (SELECT MAX(x.ORDER_DATE) FROM ORDER AS x WHERE x.CUSTOMER_ID = t1.CUSTOMER_ID AND x.ID != (SELECT MAX(x.ID) FROM ORDER AS x2 WHERE x2.CUSTOMER_ID = t1.CUSTOMER_ID)))
FROM ORDER AS a
INNER JOIN CUSTOMER AS t2 ON t1.CUSTOMER_ID = t2.ID
INNER JOIN RESTAURANT AS t3 ON t1.RESTAURANT_ID = t3.ID
ORDER BY t1;
我建议不要调用表“ ORDER”是个好习惯,因为这是MySQL使用的关键字,您可以简单地调用表“ ORDERS”来避免该问题。
这应该可以满足您的要求,如果您有任何问题,请张贴任何错误文本,以便我们更好地了解您所面临的问题。