我有一个类似于以下的表
ID | temp_hi | temp_lo ------------------------ 0 | 72 | 38 ------------------------ 1 | 56 | 33 ------------------------ 2 | 67 | 28
在单个SQL语句中是否有办法获取MAX(temp_hi)及其ID并获取MIN(temp_lo)及其ID?所以在这种情况下它将是:
(temp_hi id) 0, (temp_hi) 72, (temp_lo id) 2, (temp_low) 28
答案 0 :(得分:5)
您可以使用子查询:
SELECT * FROM data
WHERE temp_hi = (SELECT MAX(temp_hi) FROM data)
OR temp_lo = (SELECT MIN(temp_lo) FROM data);
答案 1 :(得分:3)
可能有超过最高和最低温度的ID,所以我选择一个:
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
测试数据以尝试:
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);
结果: