简体   繁体   中英

Get MAX and MIN values along with their row id?

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 

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);

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:

查询结果

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