MYSQL 选择/分组依据:如何根据组成员之一的值从结果中删除组?
考虑下面的事件表。 OrderID 字段是 Orders 表的外键。
OrderID EventType TimeAdded* Processed 1 ... 3 Hours Ago 0 2 ... 5 Minutes Ago 0 1 ... 2 Hours Ago 0 1 ... 1 Hour Ago 0 3 ... 12 Minutes ago 1 3 ... 3 Hours Ago 0 2 ... 2 Hours Ago 0
*TimeAdded 实际上是一个 mysql 日期时间字段。我在这里使用了人类可读的时间来使问题更容易阅读。
我需要获取一个结果集,其中每个 OrderID 仅一次,但前提是附加到给定订单 ID 的所有记录(其处理状态为 0)已在 15 分钟前添加。
在此示例中,订单 #2 应从结果集中省略,因为它在过去 15 分钟内添加了未处理的事件。事实上,它有一个 2 小时前未处理的事件是无关紧要的。
应包括订单 #3。尽管其中一个条目是在 12 分钟前添加的,但该条目已被处理,不应被考虑。该集合中仅应考虑“3 小时前”条目,并且它大于 15 分钟前。
应该包括订单 #1,因为附加到它的所有三个未处理事件都发生在 15 分钟前。
我不确定这是否需要使用子查询或分组依据或可能两者都使用?
伪代码:
SELECT * FROM OrderEvents WHERE Processed=0 GROUP BY OrderID
OMIT WHOLE GROUP IF GROUP_MIN(TimeAdded) >= (NOW() - INTERVAL 15 MINUTE)
我只是不确定语法是否正确?
Consider the table of events below. The OrderID field is a foreign key to an Orders table.
OrderID EventType TimeAdded* Processed 1 ... 3 Hours Ago 0 2 ... 5 Minutes Ago 0 1 ... 2 Hours Ago 0 1 ... 1 Hour Ago 0 3 ... 12 Minutes ago 1 3 ... 3 Hours Ago 0 2 ... 2 Hours Ago 0
*TimeAdded is actual a mysql date-time field. I used human readable times here to make the question easier to read.
I need to get a result set that has each OrderID, only once, but only if ALL records attached to a given order ID, that have a proceeded status of 0, have been added more than 15 minutes ago.
In this example, order #2 should be OMITTED from the result set because it has an unprocessed event added within the last 15 minutes. The fact that it has an unprocessed event from 2 hours ago is inconsequential.
Order #3 SHOULD be included. Even though one of its entries was added 12 minutes ago, that entry has already been processed, and should not be considered. Only the "3 hours ago" entry should be considered in this set, and it is greater than 15 minutes ago.
Order #1 SHOULD be included, since all three unprocessed events attached to it occurred more than 15 minutes ago.
I'm not sure if this needs to use a sub-query or group by or possibly both?
pseudo code:
SELECT * FROM OrderEvents WHERE Processed=0 GROUP BY OrderID
OMIT WHOLE GROUP IF GROUP_MIN(TimeAdded) >= (NOW() - INTERVAL 15 MINUTE)
I'm just not certain of the correct syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将完成工作(在 MySQL Workbench 中测试):
This will do the work (tested in MySQL Workbench):
我认为是这样的:
记住,我在这里盲目地工作。对于在数字上下文中使用的函数 now(),我认为 1500 是正确的。 http://dev.mysql。 com/doc/refman/5.0/en/date-and-time-functions.html#function_now
I think it's something along these lines:
Bear in mind, that I'm working blind here. I think 1500 is correct, for the function now() used in a numeric context. http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now