MySQL ORDER BY 被 GROUP BY 忽略(有效的解决方法?)
我觉得有一个简单的解决方案——我查看了 Stack Overflow 上的其他问题,但它们似乎效率低下,或者可能是我做错了。
这是我正在使用的表格的简化版本。
CREATE TABLE object_values (
object_value_id INT PRIMARY KEY,
object_id INT,
value FLOAT,
date_time DATETIME,
INDEX (object_id)
);
CREATE TABLE object_relations (
object_group_id INT,
object_id INT,
INDEX (object_group_id, object_id)
);
存在多对一关系 - 每个对象有许多对象值(每个对象平均有 150 个对象值)
我想根据 object_group_id 获取每个 object_id 的最后一个对象值(由 date_time 字段确定)。
当前查询:
SELECT a.`object_id`, a.`value`
FROM `object_values` AS a
LEFT JOIN `object_relations` AS b
ON ( a.`object_id` = b.`object_id` )
WHERE b.`object_group_id` = 105
ORDER BY a.`date_time` DESC
这会拉回所有记录 - 如果我执行 GROUP BY a.object_id
那么 ORDER BY 会被忽略
我尝试了一系列变体 - 我深表歉意,因为我知道这是这是一个常见的问题,但到目前为止尝试其他解决方案还没有完全奏效。任何帮助将不胜感激。
一些解决方案在大约 70 秒后返回结果 - 这是一个大型系统,因此需要更快一点。
I feel there is a simple solution to this -- I've looked at other questions on Stack Overflow, but they seem to be inefficient, or perhaps I'm doing them wrong.
Here are simplified versions of tables I'm working with.
CREATE TABLE object_values (
object_value_id INT PRIMARY KEY,
object_id INT,
value FLOAT,
date_time DATETIME,
INDEX (object_id)
);
CREATE TABLE object_relations (
object_group_id INT,
object_id INT,
INDEX (object_group_id, object_id)
);
There is a many-to-one relationship -- many object values per one object (150 object values on average per object)
I want to get the last object value (determined by date_time field) for each object_id based on the object_group_id.
Current Query:
SELECT a.`object_id`, a.`value`
FROM `object_values` AS a
LEFT JOIN `object_relations` AS b
ON ( a.`object_id` = b.`object_id` )
WHERE b.`object_group_id` = 105
ORDER BY a.`date_time` DESC
This pulls back all the records -- if I do a GROUP BY a.object_id
then the ORDER BY gets ignored
I have tried a series of variations -- and I apologize as I know this is a common question, but trying the other solutions hasn't quite worked so far. Any help would greatly appreciated.
Some of the solutions came back with results about 70 seconds later -- this is a large system so needs to be a bit faster.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果单个组中永远不会出现重复的
date_time
,则可以省略最后的GROUP BY
。You can omit the final
GROUP BY
if there will never be duplicatedate_time
in a single group.尝试这个没有分组依据的版本,使用子查询来提取每个对象的最大日期:
由于您在 where 子句中指定了组 ID,因此不需要左联接,因此我将该组作为联接中的主表。这可以通过多种方式完成。如果 WHERE 只是更改为 AND,则子查询也可以移至连接子句。
Try this version without a group by, using a sub-query to pull the max date for each object:
The left join was unneeded since you specified the group ID in the where clause, so I made the group the main table in the join. This could be done several ways. The sub query could also be moved to the join clause if WHERE is just changed to AND.