开发者

Getting a sorted distinct list from mySQL

Goal

I'l like to get a list of unique FID's ordered by the the one which has most recently been changed. In this sample table it should return FIDs in the order of 150, 194, 122

Example Data

ID    FID    changeDate
----------------------------------------------
1     194    2010-04-01
2     122    2010-04-02
3     194    2010-04-03
4     150    2010-04-04

My Attempt

I thought distinct and order by would do the trick. I initially tried:

SELECT distinct `FID` FROM `tblHistory` WHERE 1 ORDER BY changeDate desc
# Returns 150, 122, 194

using GROUP BY has the same result. I'm just barely a SQL amateur, and I'm a bit hung up. What seems to be happening is the aggregating functions find the first occurrence of each and then perform the sort.

I开发者_运维百科s there a way I can get the result I want straight from mySQL or do I have to grab all the data and then sort it in the PHP?


This worked for me:

SELECT FID
FROM tblHistory
GROUP BY FID
ORDER BY MAX(changeDate) DESC;


Okay, been reading questions on the site since I asked this one, and came up with an answer that seems to work, although I hope perhaps someone else may shed light on a simpler way:

SELECT t1.FID, t1.CD
FROM (
  SELECT FID, max(changeDate) as CD
  FROM sorted
  GROUP BY FID
) as t1 
WHERE 1 
order by t1.CD desc

Seems to get the results I expect. I didn't know subqueries existed until a few minuets ago. I'm a real SQL newbie.


select * from tbl A 
where changeDate = 
    (select max(changeDate) from tbl where tbl.fid = A.fid)
order by changeDate desc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜