我有2个表,orders
和orderNotes
:
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
答案 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 |
+---------+---------------------+
答案 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