|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
Query Help
I am having trouble getting a query to work.
I have a table along the following columns ID | DATE | USER | DATA The table has many rows, with each user having between 0 and many entries per day. I want a query that returns the latest 50 records based on DATE, but I only want the latest entry for each USER. I can obviously use a query along the lines of SELECT * from table-name ORDER BY date DESC but that would return many records for each USER, how can I limit so I get a maximum of 1 record per user ( i.e. their latest one ) any help appreciated thanks |
|
#2
|
||||
|
||||
|
Code:
SELECT d.id
, d.date
, d.user
, d.data
FROM ( SELECT user
, MAX(date) as maxdate
FROM daTable
GROUP
BY user ) AS u
INNER
JOIN daTable AS d
ON d.user = u.user
AND d.date = u.maxdate
ORDER
BY d.date DESC LIMIT 50
|
|
#3
|
|||
|
|||
|
Hi R937
Thanks for the query, it looks impressive. I am trying to break the query down so I can learn for the future. I don't understand why the JOIN is required. It looks to me like Code:
SELECT user , MAX(date) as maxdate FROM daTable GROUP BY user will do it by itself. What am I missing here ? Thanks again |
|
#4
|
|||
|
|||
|
Oh, I see it now - the subquery finds the latest date for a user, the JOIN pulls back the record with the latest date found in the first query.
I am still left with one slight glitch, if a user has multiple records on a date then the join brings back all of them - I want a maximum of one record per user. thanks |
![]() |
| Viewing: Dev Shed Forums > Databases > MySQL Help > Query Help |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|