简化,但对于像:
这样的表格id time distance price 1 20 500 8 2 50 500 10 3 90 500 12 4 80 1000 17 5 170 1000 11 6 180 1000 13 7 19 800 12
我希望获得距离为500和1000的最快时间的行,即
id time distance price 1 20 500 8 4 80 1000 17
如果我这样做
select min(time) from table
可以很好地找到价格,但我无法获得ID和价格 - 只有所有ID /价格的最大/最小/平均/第一个值。
我可以通过多次查找来实现 - 例如
select * from table where distance = 500 and time = 20 select * from table where distance = 1000 and time = 80
但是有一种更好的方法,不涉及1 +(距离数)查询(或者至少提供一个结果集,即使在内部使用该数量的查询)
答案 0 :(得分:2)
您需要使用内部选择:
SELECT t.id, t.time, t.distance, t.price
FROM table t
JOIN (SELECT MIN(time) as min_time, distance
FROM table
GROUP BY distance) as tmp
ON (t.distance = tmp.distance AND t.time = tmp.min_time)
WHERE t.distance IN (500, 1000)
答案 1 :(得分:0)
您需要将min内容放入having子句中,因此您的查询将为select * from table group by distance having min(distance);
(另)
或者您可以使用subquerys找出:
select * from table where distance = (select distance from table where min(time)) and time = select min(time) from table)
(也未经测试:))
答案 2 :(得分:0)
这个怎么样......准确地说你正在寻找什么(测试)
select * from Table1 where time in (select min(time) from table1 where distance = 500 or distance = 1000 group by distance) and (distance = 500 or distance = 1000)
答案 3 :(得分:0)
只是订购和限制。那么你在1次查询中获得最快的500距离。
select * from thetable where distance = 500 ORDER BY time ASC LIMIT 1
答案 4 :(得分:0)
试试这个 -
SELECT t1.* FROM table1 t1
JOIN (SELECT distance, MIN(time) min_time FROM table11 WHERE distance = 500 OR distance = 1000 GROUP BY distance) t2
ON t1.distance = t2.distance AND t1.time = t2.min_time;
答案 5 :(得分:0)
SELECT * FROM tblData INNER JOIN (SELECT MIN(TIME) AS minTime, distance FROM tblData WHERE distance IN (500,1000) GROUP BY distance) AS subQuery ON tblData.distance = subQuery.distance AND tblData.time = subQuery.minTime