SQL get all of the users last search

半城伤御伤魂 提交于 2021-02-11 15:02:35

问题


I can easily get the users searches, but I would like to get all of the users LAST search. For example, the SQL code below will get this specific users last search.

select uid, itemDescription, date from SEARCH 
    WHERE date BETWEEN '2020-03-01' AND '2020-03-30' 
        AND uid = "000-000-000-000-000"
    ORDER BY date DESC
    LIMIT 1

If I try to edit this and remove the uid = "", this wont work since it will limit to one search. If I remove the LIMIT 1 also and add a GROUP BY uid, its not picking up the last entry.

Any idea would be greatly appreciated.


回答1:


You can use a correlated subquery:

select uid, itemDescription, date
from SEARCH s
where s.date BETWEEN '2020-03-01' AND '2020-03-30' and
      s.date = (select max(s2.date)
                from search s2
                where s2.uid = s.uid and
                      s2.date = s.date
               );

For performance, you want an index on search(uid, date).

You can also try window functions:

select s.*
from (select s.*,
             row_number() over (partition by uid order by date desc) as seqnum
      from search s
      where .date between '2020-03-01' and '2020-03-30' 
     ) s
where seqnum = 1;


来源:https://stackoverflow.com/questions/60932823/sql-get-all-of-the-users-last-search

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