问题
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