检测表上的最后一个活动

时间:2014-08-05 17:55:22

标签: mysql

我有2个表,ordersorderNotes

orders:

orderID | customerID | orderName
--------+------------+-----------
   1    |     1      |  Test
   2    |     1      |  1234
   3    |     1      |  Test 2
   4    |     2      |  ABC Test

orderNotes:

noteID | orderID |      postedDate      | message
-------+---------+----------------------+----------
   1   |    1    | 2014-08-01 08:00:06  |  Testing
   2   |    1    | 2014-08-04 13:15:45  |  Hello
   3   |    2    | 2014-07-31 11:11:50  |  Hi, World
   4   |    2    | 2014-08-01 12:16:32  |  Test 123

...我想你明白了

我想要做的是检测是否有任何订单在X小时内更新。

我想出了这个:

SELECT orders.orderID, postedDate FROM orders
JOIN orderNotes ON orders.orderID = orderNotes.orderID
WHERE orders.customerID = 1
AND postedDate <= NOW() - INTERVAL 2 HOUR

但是,这会检查orderNotes中的每一行。如何才能检查 last 行?我想知道是否有任何订单(customerID = 1)在2小时内没有更新。

以下是我当前SQL的演示:http://sqlfiddle.com/#!2/d5fc2e/1

2 个答案:

答案 0 :(得分:1)

创建一个具有最大日期的视图

CREATE VIEW maxOrderNotes AS
SELECT
    orderID,
    MAX(`postedDate`) AS postedDate
FROM
    orderNotes
GROUP BY
    orderID;

使用联接中的视图

SELECT orders.orderID, postedDate FROM orders
JOIN maxOrderNotes ON orders.orderID = maxOrderNotes.orderID
WHERE orders.customerID = 1
AND postedDate <= NOW() - INTERVAL 2 HOUR;

+---------+---------------------+
| orderID | postedDate          |
+---------+---------------------+
|       1 | 2014-08-04 10:15:45 |
|       2 | 2014-08-01 12:16:32 |
+---------+---------------------+

sqlfiddle

答案 1 :(得分:0)

我找到了似乎有效的解决方案。

SELECT orders.orderID, MAX(postedDate) AS maxDate
FROM orders
JOIN orderNotes ON orders.orderID = orderNotes.orderID
WHERE orders.customerID = 1
GROUP BY orders.orderID
HAVING MAX(postedDate) <= NOW() - INTERVAL 2 HOUR

DEMO:http://sqlfiddle.com/#!2/d5fc2e/16