Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: get highest of one and lowest value of another field in one row

Tags:

mysql

max

min

I have a (MySQL) table with two date/time fields: start and end (each of the type datetime). I need a query which delivers me the lowest value from start and the highest value of end for a certain user and a defined date. I finally suceeded with the following query:

SELECT job.id, job.user_id, job.start, last.end 
FROM job
    JOIN job AS last 
        ON job.user_id = last.user_id 
            AND DATE( job.start ) = DATE( last.start ) 
            AND last.end = (SELECT max( last2.end) 
                            FROM job AS last2 
                            WHERE last2.user_id = last.user_id 
                                AND DATE( last2.end ) = DATE( last.end ))
WHERE job.user_id = 1 
    AND DATE( job.start ) = '2012-05-28' 
ORDER BY job.start ASC 
LIMIT 0,1

Even though it works, it does not 'feel' right. Is there an easier way to do this? Any help and hints is/are much appreciated. Thanks!

Example data:

user_id     start               end
1       2012-05-28 07:13:00     2011-04-26 07:45:00
1       2012-05-28 08:15:00     2011-04-26 08:50:00
1       2012-05-28 05:32:00     2011-04-26 05:51:00
1       2012-05-28 08:50:00     2011-04-26 09:50:00
1       2012-05-28 15:10:00     2011-04-26 15:40:00
1       2012-05-27 16:11:00     2011-04-26 16:46:00
2       2012-05-28 09:50:00     2011-04-26 10:35:00
like image 366
Andreas Avatar asked Dec 20 '25 06:12

Andreas


1 Answers

Select user_id
  , Min( start ) As MinStart
  , Max( end ) As MaxEnd
From job
Where Date( start ) = '2012-05-28'
  And user_id = 1
Group By user_id, Date( start )

Based on your comment that {1, 2012-5-28 5:32:00 2011-04-26 15:40:00} is the expected output (which is why sample output is so important), that indicates that the start and end date values do not necessarily have to relate to an actual row's value. For example, there is no row with the combination of values in your sample data. Given that, the solution is simpler.

I grouped on Date( start ) only to show that if you remove the Where clause, you can determine the min and max start dates by start day. Given that you are filtering on both, you can simplify the query to:

Select user_id
  , Min( start ) As MinStart
  , Max( end ) As MaxEnd
From job
Where Date( start ) = '2012-05-28'
  And user_id = 1
Group By user_id

SQL Fiddle verison

like image 162
Thomas Avatar answered Dec 22 '25 00:12

Thomas