Skip to content
Advertisement

Select one row with MAX(column) for known other several columns without subquery

My table contains votes of users for different items. It has the following fields:

I understand how to get the last vote of #user# for #item#, but it uses subquery:

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?

There is a second part to this question: Count rows with DISTINCT(several columns) and MAX(another column)

Advertisement

Answer

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:

An index on either (user_id, item_id, utc_time) or (item_id, user_id, utc_time) will be good for efficiency.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement