Select one row with MAX(column) for known other several columns without subquery(为没有子查询的已知其他几列选择具有 MAX(column) 的一行)
问题描述
我的表格包含用户对不同项目的投票.它有以下字段:
My table contains votes of users for different items. It has the following fields:
id, user_id, item_id, vote, utc_time
我了解如何为 #item# 获得 #user# 的最后一票,但它使用子查询:
I understand how to get the last vote of #user# for #item#, but it uses subquery:
SELECT votes.*, items.name, items.price
FROM votes JOIN items ON items.id = votes.item_id
WHERE user_id = #user# AND item_id = #item#
AND utc_time = (
SELECT MAX(utc_time) FROM votes
WHERE user_id = #user# AND item_id = #item#
)
它有效,但对我来说看起来很愚蠢......应该有一种更优雅的方式来获得这个记录.我尝试了这里建议的方法,但我还不能让它工作,所以我会感谢你的帮助:如何在 SQL 中选择具有 MAX(列值)、DISTINCT 的行?
It works, but it looks quite stupid to me... There should be a more elegant way to get this one record. I tried the approach suggested here, but I cannot make it work yet, so I'll appreciate your help: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
这个问题还有第二部分:Count rows with DISTINCT(几列)和MAX(另一列)
There is a second part to this question: Count rows with DISTINCT(several columns) and MAX(another column)
推荐答案
您只需要结果中的一行,即具有 MAX(utc_time)
的行.在 MySQL 中,有一个 LIMIT
子句,您可以使用 ORDER BY
:
You want just one row from the result, the one with MAX(utc_time)
. In MySQL, there is a LIMIT
clause you can apply with ORDER BY
:
SELECT votes.*, items.name, items.price
FROM votes JOIN items ON items.id = votes.item_id
WHERE user_id = #user# AND item_id = #item#
ORDER BY votes.utc_time DESC
LIMIT 1 ;
(user_id, item_id, utc_time)
或 (item_id, user_id, utc_time)
上的索引会提高效率.
An index on either (user_id, item_id, utc_time)
or (item_id, user_id, utc_time)
will be good for efficiency.
这篇关于为没有子查询的已知其他几列选择具有 MAX(column) 的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为没有子查询的已知其他几列选择具有 MAX(column) 的一行


- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01