我试图编写一个MySQL查询,根据查询到TABLE2
的结果从TABLE1
中选择结果。像这样:
SELECT route_id FROM trips WHERE trip_id =
SELECT trip_id FROM stop_times WHERE
stop_id=<ID GOES HERE> LIMIT 1
但这不起作用,所以我尝试了这个:
SELECT route_id FROM trips WHERE trip_id
INNER JOIN(
SELECT trip_id FROM stop_times WHERE stop_id=<ID GOES HERE> LIMIT 1
)
它也不起作用。我收到此错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN(SELECT trip_id FROM stop_times WHERE stop_id="16817" LIMIT 1)
LIMIT 0' at line 1
答案 0 :(得分:1)
您的原始查询应如下所示:
SELECT t.route_id
FROM trips t
WHERE t.trip_id = (SELECT st.trip_id
FROM stop_times st
WHERE st.stop_id = <ID GOES HERE>
LIMIT 1
);
我认为这通常会写成:
SELECT t.route_id
FROM stop_times st JOIN
trips t
ON t.trip_id = st.trip_id
WHERE st.stop_id = <ID GOES HERE>
LIMIT 1;
这假定您想要返回一行。
答案 1 :(得分:0)
你的子查询应该是:
SELECT route_id
FROM trips
WHERE trips.trip_id =
(
SELECT stop_times.trip_id
FROM stop_times
WHERE stop_id = <ID GOES HERE>
LIMIT 1
)
答案 2 :(得分:0)
有两种选择:
SELECT route_id FROM trips WHERE trip_id in (SELECT trip_id FROM stop_times WHERE stop_id=<ID GOES HERE> LIMIT 1)
或者更容易:
select t.route_id from trips t, stop_times s where t.trip_id = s.trip_id and s.stop_id= <ID GOES HERE> LIMIT 1