gpt4 book ai didi

php - MySQL 中的子选择

转载 作者:行者123 更新时间:2023-11-29 11:26:06 25 4
gpt4 key购买 nike

我有下表,代表公交车及其停靠点。

bus_table

bus stop_no station_id
1 1 1
1 2 2
1 3 3
2 1 7
2 2 8
2 3 9
3 1 3
3 2 4
3 3 5
3 4 6
3 5 7

我想从 1 号车站到 9 号车站。

我可以为此编写什么查询?

最佳答案

举个例子。显然,这个解决方案不是递归的 - 但您可以继续迭代公交车路线,直到从 A 到达 B。

DROP TABLE IF EXISTS bus_routes;


CREATE TABLE bus_routes
(bus_no INT NOT NULL
,stop_no INT NOT NULL
,station_id INT NOT NULL
,PRIMARY KEY(bus_no,stop_no)
);

INSERT INTO bus_routes VALUES
(1,1,1),
(1,2,2),
(1,3,3),
(2,1,7),
(2,2,8),
(2,3,9),
(3,1,3),
(3,2,4),
(3,3,5),
(3,4,6),
(3,5,7);

SELECT a_from.bus_no
, a_from.station_id start_from
, b_from.station_id first_change_at
, b_from.bus_no to_bus
, c_from.station_id then_change_at
, c_from.bus_no to_bus
, c_to.station_id alighting_at
FROM bus_routes a_from
JOIN bus_routes a_to
ON a_to.bus_no = a_from.bus_no
AND a_to.stop_no > a_from.stop_no
JOIN bus_routes b_from
ON b_from.station_id = a_to.station_id
JOIN bus_routes b_to
ON b_to.bus_no = b_from.bus_no
AND b_to.stop_no > b_from.stop_no
JOIN bus_routes c_from
ON c_from.station_id = b_to.station_id
JOIN bus_routes c_to
ON c_to.bus_no = c_from.bus_no
AND c_to.stop_no > c_from.stop_no
WHERE a_from.station_id = 1
AND c_to.station_id = 9;

+--------+------------+-----------------+--------+----------------+--------+--------------+
| bus_no | start_from | first_change_at | to_bus | then_change_at | to_bus | alighting_at |
+--------+------------+-----------------+--------+----------------+--------+--------------+
| 1 | 1 | 3 | 3 | 7 | 2 | 9 |
+--------+------------+-----------------+--------+----------------+--------+--------------+

关于php - MySQL 中的子选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38170362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com