SELECT f.flight_id
FROM flights f
JOIN flightsinfo AS i ON f.flight_code = i.flight_code
JOIN airports AS a ON i.dep_airport_id = a.airport_id
JOIN cities as c ON a.city_id = c.city_id AND city_name = 'New York'
JOIN airports AS b ON i.arr_airport_id = b.airport_id
JOIN cities AS v ON v.city_id = b.city_id AND v.city_name = 'Budapest'
HAVING f.price = MIN(price)
我正试图在两个随机城市之间以最低价格获得flight_id
航班。最后一行发生错误
有子句
中的未知列
当我尝试使用where / from error时:
无效使用群组功能。
有什么想法吗?
答案 0 :(得分:1)
如果您需要基于订单的第一条记录,只需使用SELECT TOP 1
或TAKE 1
,具体取决于rdbms,并按您需要订购的字段排序。
SQL SERVER 2008
SELECT TOP 1
f.flight_id
FROM
flights f
JOIN flightsinfo AS i ON f.flight_code = i.flight_code
JOIN airports AS a ON i.dep_airport_id = a.airport_id
JOIN cities AS c ON a.city_id = c.city_id
AND city_name = 'New York'
JOIN airports AS b ON i.arr_airport_id = b.airport_id
JOIN cities AS v ON v.city_id = b.city_id
AND v.city_name = 'Budapest'
ORDER BY
f.price
<强>的MySQL 强>
SELECT
f.flight_id
FROM
flights AS f
JOIN flightsinfo AS i ON f.flight_code = i.flight_code
JOIN airports AS a ON i.dep_airport_id = a.airport_id
JOIN cities AS c ON a.city_id = c.city_id
AND city_name = 'New York'
JOIN airports AS b ON i.arr_airport_id = b.airport_id
JOIN cities AS v ON v.city_id = b.city_id
AND v.city_name = 'Budapest'
ORDER BY
f.price
LIMIT 1;
答案 1 :(得分:0)
使用公用表格表达式(cte)查找价格最低的航班。 (如果它是平局,将返回两个航班。)
WITH CTE (flight_id, price) AS
(
SELECT f.flight_id, f.price
FROM flights f
JOIN flightsinfo AS i ON f.flight_code = i.flight_code
JOIN airports AS a ON i.dep_airport_id = a.airport_id
JOIN cities as c ON a.city_id = c.city_id AND city_name = 'New York'
JOIN airports AS b ON i.arr_airport_id = b.airport_id
JOIN cities AS v ON v.city_id = b.city_id AND v.city_name = 'Budapest'
)
select flight_id, price
from cte
where price = (select min(price) from cte)
或者,JamieD77的ANSI SQL版本回答:
SELECT
f.flight_id
FROM
flights AS f
JOIN flightsinfo AS i ON f.flight_code = i.flight_code
JOIN airports AS a ON i.dep_airport_id = a.airport_id
JOIN cities AS c ON a.city_id = c.city_id
AND city_name = 'New York'
JOIN airports AS b ON i.arr_airport_id = b.airport_id
JOIN cities AS v ON v.city_id = b.city_id
AND v.city_name = 'Budapest'
ORDER BY
f.price
FETCH FIRST 1 ROW WITH TIES
WITH TIES
表示如果它是平局就会返回多行!