从连接表中查询日期列

时间:2015-04-27 16:54:05

标签: mysql sql join

这是架构:

Customer (Customer_ID, Name, Address, Phone),
Porder (Customer_ID, Pizza_ID, Quantity, Order_Date), 
Pizza (Pizza_ID, Name, Price).

我想让所有在过去30天内订购比萨饼的顾客根据Order_Date& amp;谁在过去30天里花了最多的钱。这些可以组合成一个吗?

以下是我正在尝试的内容,我不确定DATEDIFF或查询将如何计算总金额。

SELECT customer.customer_ID, customer.name FROM customer 
JOIN porder ON customer.customer_ID = porder.customer_ID
GROUP BY customer.customer_ID, customer.name
WHERE DATEDIFF(porder.porder_date,getdate()) between 0 and 30

过去30天谁花的钱最多?

SELECT porder.customer_ID, porder.pizza_id, porder.quantity FROM order 
JOIN pizza ON porder.pizza_ID = pizza.pizza_ID
GROUP BY porder.customer_ID
WHERE MAX((porder.quantity * pizza.price)) && DATEDIFF(porder.porder_date,getdate()) between 0 and 30

2 个答案:

答案 0 :(得分:2)

请记住,函数是用于查询优化器的黑盒子,因此您最好使查询适合索引,而不是相反。

WHERE DATEDIFF(order.order_date,getdate()) between 0 and 30
可以重写

,以便查询在order_date

上使用普通索引
WHERE order.order_date >= CURRENT_DATE - INTERVAL 30 DAY

过去30天内花费最多的人

SELECT 
  o.customer_id, SUM(p.price * o.quantity)
FROM 
  order o
  INNER JOIN pizza p 
    ON o.pizza_id = p.pizza_id
WHERE 
  order_date >= CURRENT_DATE - INTERVAL 30 DAY
GROUP BY o.customer_id
ORDER BY SUM(p.price * o.quantity) DESC
LIMIT 1

答案 1 :(得分:0)

一旦您整理了表格,并将订单细节与订单分开,就需要考虑一些事项。

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT x.*
     , IF(x.i = y.maxi,1,0) is_biggest 
  FROM ints x 
  LEFT 
  JOIN (SELECT MAX(i) maxi FROM ints) y 
    ON y.maxi = x.i;
+---+------------+
| i | is_biggest |
+---+------------+
| 0 |          0 |
| 1 |          0 |
| 2 |          0 |
| 3 |          0 |
| 4 |          0 |
| 5 |          0 |
| 6 |          0 |
| 7 |          0 |
| 8 |          0 |
| 9 |          1 |
+---+------------+