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) 的一行
基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
