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

此生再无相见时 提交于 2019-12-07 20:09:22

问题


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

id, user_id, item_id, vote, utc_time

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#
            )

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)


回答1:


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 ;

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




回答2:


Simple: if the date/time is the maximum date there will not exist a "higher" (more recent) date/time (for the same {user,item} ).

SELECT vo.*
     , it.name, it.price
  FROM votes vo
  JOIN items it ON it.id = vo.item_id
 WHERE vo.user_id = #user# AND vo.item_id = #item#
   AND NOT EXISTS (
       SELECT *
       FROM votes nx
       WHERE nx.user_id = vo.user_id
       AND nx.item_id = vo.item_id
       AND nx.utc_time > vo.utc_time
       );


来源:https://stackoverflow.com/questions/14430260/select-one-row-with-maxcolumn-for-known-other-several-columns-without-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!