Help with MySQL query that is based on the number of clicks on an item
-
25-09-2019 - |
Question
I have a table setup like this (simplified for example):
user_id
item_id
click_dt
Each item_id has many user_id's. Basically it's storing the clicks on items, associated to a user_id.
I want to query through this and list only the latest user_id for each item_id, based on click_dt.
So if there are 5 clicks for item_id 55, the last click or click_dt DESC would be the record to show....
Make sense? Any help would be awesome... thanks!
Solution
Use:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.item_id,
MAX(t.click_dt) AS max_date
FROM YOUR_TABLE t
GROUP BY t.item_id) y ON y.item_id = x.item_id
AND y.max_date = x.clicked_dt
Alternate:
SELECT x.item_id,
x.user_id,
x.click_dt
FROM (SELECT t.item_id,
t.user_id,
t.click_dt,
CASE
WHEN @item = t.item_id THEN @rownum := @rownum + 1
ELSE @rownum := 1
END AS rk,
@item := t.item_id
FROM YOUR_TABLE t
JOIN (SELECT @rownum := 0, @item := 0) r
ORDER BY t.itemid, click_dt DESC) x
WHERE x.rk = 1
OTHER TIPS
Try this:
SELECT user_id,item_id,click_dt FROM
(
SELECT MAX(click_dt) AS LastClick_dt,item_id FROM aTable
GROUP BY item_id
) As LastClick
INNER JOIN aTable
ON aTable.itemid = LastClick.item_id
AND aTable.click_dt = LastClick.LastClick_dt
The subselect part will give the latest click for each item_id, and then you can join this to the original table to retrieve the matching user_id.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow