Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MAX and MIN values along with their row id?

Tags:

mysql

I have a table similar to the following

ID   | temp_hi | temp_lo
------------------------
  0  |    72   |   38
------------------------
  1  |    56   |   33
------------------------
  2  |    67   |   28

Is there a way in a single SQL statement to grab the MAX(temp_hi) and it's ID and get the MIN(temp_lo) and it's ID? So in this case it would be:

(temp_hi id) 0, (temp_hi) 72, (temp_lo id) 2, (temp_low) 28 
like image 644
dstach Avatar asked Feb 23 '23 10:02

dstach


2 Answers

You could use a subquery:

SELECT * FROM data 
WHERE temp_hi = (SELECT MAX(temp_hi) FROM data)
OR temp_lo = (SELECT MIN(temp_lo) FROM data);
like image 69
Raymond Hettinger Avatar answered Feb 25 '23 00:02

Raymond Hettinger


There could be more than an ID with max and min temperature, so I just pick one:

SELECT 
  (SELECT ID FROM temp ORDER BY temp_hi DESC LIMIT 1) AS max_temp_id, 
  MAX(temp_hi) AS max_temp,
  (SELECT ID FROM temp ORDER BY temp_lo LIMIT 1) AS min_temp_id,
  MIN(temp_lo) AS min_temp
FROM temp

Test data to try it:

CREATE TABLE IF NOT EXISTS `temp` (
  `ID` int(11) NOT NULL,
  `temp_hi` int(11) NOT NULL,
  `temp_lo` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


INSERT INTO `temp` (`ID`, `temp_hi`, `temp_lo`) VALUES
(0, 72, 38),
(1, 56, 33),
(2, 67, 28);

Result:

query results

like image 28
stivlo Avatar answered Feb 25 '23 00:02

stivlo