infinets Posted April 16, 2007 Share Posted April 16, 2007 Hi, I have data as shown below. park_id item pay_date -------- ------ - ----------- 1 red 2007-01-04 1 blue 2007-03-05 2 red 2007-02-02 3 blue 2007-01-20 I want to be able to select distinct rows but selecting the row with the most recent date e.g. want to output park_id item pay_date -------- ------ - ----------- 1 blue 2007-03-05 2 red 2007-02-02 3 blue 2007-01-20 That particular park_id 1 selected because it's date was the most recent. Help please... Quote Link to comment https://forums.phpfreaks.com/topic/47192-solved-select-particular-disctinct-row-based-on-date/ Share on other sites More sharing options...
bubblegum.anarchy Posted April 16, 2007 Share Posted April 16, 2007 The following code looks all kinds or wrong to me even through the results appear correct: SELECT * FROM ( SELECT * FROM park ORDER BY pay_date DESC ) AS derived GROUP BY id ORDER BY pay_date DESC; Quote Link to comment https://forums.phpfreaks.com/topic/47192-solved-select-particular-disctinct-row-based-on-date/#findComment-230178 Share on other sites More sharing options...
Barand Posted April 16, 2007 Share Posted April 16, 2007 It does rely on the assumption that values from those fields not specified in the GROUP BY clause will come from the first record encountered in the group. In my experience they do, BUT the manual does say those values are unpredictable. Also MySql is lenient in allowing the group by to exclude some selected fields I'd play safe and use a more portable version like this (sales table 10,000+ rows, 100 products, query time 0.005 sec) SELECT s.prodcode, s.salesvalue, s.datesold FROM sales s INNER JOIN (SELECT prodcode, MAX(datesold) as latest FROM sales GROUP BY prodcode) as b ON s.prodcode = b.prodcode AND s.datesold = b.latest For your table: SELECT p.park_id, p.item, p.pay_date FROM park p INNER JOIN (SELECT park_id, MAX(pay_date) as latest FROM park GROUP BY park_id) as b ON p.park_id = b.park_id AND p.pay_date = b.latest Quote Link to comment https://forums.phpfreaks.com/topic/47192-solved-select-particular-disctinct-row-based-on-date/#findComment-230283 Share on other sites More sharing options...
bubblegum.anarchy Posted April 16, 2007 Share Posted April 16, 2007 oh yes, that is great Barand... and ORDER BY pay_date DESC Quote Link to comment https://forums.phpfreaks.com/topic/47192-solved-select-particular-disctinct-row-based-on-date/#findComment-230764 Share on other sites More sharing options...
infinets Posted April 17, 2007 Author Share Posted April 17, 2007 Thanks, that works great... was driving me nuts!! Quote Link to comment https://forums.phpfreaks.com/topic/47192-solved-select-particular-disctinct-row-based-on-date/#findComment-230855 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.