简体   繁体   中英

Select only one entry per ID

I'm working with a system that perodically updates itself, within this system I try to select the highest 500 and list them. However, the problem is that I sort it by a varchar that contains a date in the format of 2013-07-08, this is a relic and for the time being I am annoyingly not allowed to change this to a proper date for easy sorting.

My question is, how can I select only 1 of the following 3 pretended results?

id| value | ownerid | date

1| 21300 | 1       | 2013-07-08
2| 21300 | 1       | 2013-07-08
3| 21300 | 1       | 2013-07-08

What I need done is to select one entry from each ownerid, which is the one with the highest value (if it's all the same it doesn't really matter which entry, just that it's only one!)

This is using a mysql database with PDO as the database layer.

Thankful for any and all help!

Use a sub-query with a GROUP BY to get a particular id for each day (max or min for example) then JOIN that against the table to get the rest of the details:

SELECT a.id, a.value, a.ownerid, a.date
FROM SomeTable a
INNER JOIN
(
    SELECT date, MAX(id) AS MaxId
    FROM SomeTable
    GROUP BY date
) b
ON a.date = b.date
AND a.id = b.MaxId

Modified version to get the highest value row for each day. As value isn't unique I have done a further sub select to get the highest id for that highest value. Without this you could get multiple rows returned for a day. If there is zero chance of the other values every being different you could use DISTINCT to remove the multiples, but normally not possible to be certain of that.

SELECT a.id, a.`value`, a.ownerid, a.`date`
FROM SomeTable a
INNER JOIN
(
    SELECT `date`, MAX(`value`) AS MaxVal
    FROM SomeTable
    GROUP BY `date`
) b
ON a.`date` = b.`date`
AND a.`value` = b.MaxVal
INNER JOIN
(
    SELECT `date`, `value`, MAX(id) AS MaxId
    FROM SomeTable
    GROUP BY `date`, `value`
) c
ON b.`date` = c.`date`
AND b.MaxVal = c.`value`
AND a.id = c.MaxId
SELECT * 
FROM [table] 
ORDER BY STR_TO_DATE(yourdatefield, '%m/%d/%Y') DESC 
LIMIT 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM