我有多个代表航班数据的表:
航班:
ID | NMB | DATE
1 | CA1 | 2017-05-26
2 | CA1 | 2017-05-27
3 | CA2 | 2017-05-26
4 | CA2 | 2017-05-27
机场:
ID | NAME
1 | JFK
2 | LAX
flights_arrival:
ENTITY_ID (flights) | TARGET_ID (airports)
1 | 1
2 | 1
3 | 2
4 | 2
flights_price:
ENTITY_ID (flights) | VALUE
1 | 455
2 | 650
3 | 750
4 | 880
我试图为每个到达机场的每个航班选择最低价格。我想要的是这个:
ID | ARRIVAL | PRICE
1 | 1 | 455
3 | 2 | 750
这是我构建的SQL查询,但MIN
上应用的flights_price
函数不仅返回航班的最低价格,而是返回所有条目:
SELECT
f.id AS id,
fa.target_id AS arrival,
MIN(fp.value) AS price
FROM flights_price AS fp
JOIN flights AS f ON fp.entity_id=f.id
JOIN flights_arrival AS fa ON fa.entity_id=f.id
WHERE
fa.target_id IN (1, 2)
GROUP BY
fa.target_id,
fp.value,
f.id;
我做错了什么?我也试过子查询但没有成功。
答案 0 :(得分:0)
value
中有GROUP BY
列,如果您需要在其上应用汇总列,则需要将其从GROUP BY
中移除(否则它只会应用于一个值仅限每个组,使聚合成为冗余),例如:
SELECT fa.entity_id, f.name, fa.target_id, a.name, MIN(value)
FROM flights_arrival fa JOIN flights_price fp ON fa.entity_id = fp.flights
JOIN flights f ON fa.entity_id = f.id
JOIN airports a ON fa.target_id = a.id
WHERE fa.target_id IN (1,2)
GROUP BY fa.entity_id, f.name, fa.target_id, a.name;
答案 1 :(得分:0)
尝试此查询 -
/cache/test-uri/
从您的输出和您尝试过的查询中,我猜您只需要有抵达和价格的航班。这就是为什么不需要使用航班表。您还可以在分组依据之前添加WHERE过滤器,以获取特定ID的结果,而不是所有航班。
entity_id列可能位于 SELECT 语句中,即使它不存在于 GROUP BY 中,因为数据库是 MySQL 。与 flights_price 表一样, entity_id 也是唯一的,因此 fp.entity_id 将获得最低价格的正确值。