0

我有一张表bus_stops,其中包含巴士站的路线 ID,如下所示:

 sl_no     route_id                    stop_name
-------------------------------------------------------------
  1          1234                       stop1
  2          1234                       stop2
  3          1235                       stop7
  4          1235                       stop8
  5          5678                       stop1
  6          5678                       stop2

我想要一个包含 stop1 和 stop2 的 route_id(对于 stop1 作为 From station 和 stop2 作为 To station 我想获得 1234,但不是对于“stop2 as From Staion”和“stop1 as To Station”)。

我写了这个查询:

SELECT DISTINCT route_id FROM bus_stops AS myAlias
WHERE EXISTS ( SELECT * FROM bus_stops WHERE route_id = myAlias.route_id AND stops = 'stop1' )
  AND EXISTS ( SELECT * FROM bus_stops WHERE route_id = myAlias.route_id AND stops = 'stop2' )

但它返回 route_id 为“stop1 作为 From station 和 stop2 作为 To station”和“stop2 as From Staion and stop1 as To Station”

4

2 回答 2

0

使用 JOIN 执行此操作,以获取停靠点位于起点站之后的路线(即,终点站的 sl_no 比起点站大):-

SELECT a.route_id, a.stop_name, b.stop_name
FROM bus_stops a
INNER JOIN bus_stops b 
ON a.route_id = b.route_id
AND a.stop_name = 'stop1'
AND b.stop_name = 'stop2'
AND a.sl_no < b.sl_no
于 2013-06-20T08:19:56.267 回答
0

如果我正确理解了您的要求,您可以试试这个:

SELECT
    route_id
FROM 
    bus_stops
WHERE
    stop_name IN ('stop1','stop2')
GROUP BY
    route_id
HAVING 
    COUNT(*) = 2

更新:并按照您想要的顺序往返:

SELECT
    tmp.route_id,
    GROUP_CONCAT(IF(tmp.smin = bs.sl_no AND bs.stop_name = 'stop1','from stop1','') SEPARATOR '') as bfrom,
    GROUP_CONCAT(IF(tmp.smax = bs.sl_no AND bs.stop_name = 'stop2','to stop2','') SEPARATOR '') as bto
FROM (
    SELECT
        route_id,
        MIN(sl_no) as smin,
        MAX(sl_no) as smax
    FROM 
        bus_stops
    WHERE
        stop_name IN ('stop1','stop2')
    GROUP BY
        route_id
    HAVING 
        COUNT(*) = 2
) as tmp
INNER JOIN bus_stops bs
    ON bs.route_id = tmp.route_id
GROUP BY
    tmp.route_id
HAVING
    bfrom <> ''
    AND bto <> ''
于 2013-06-20T07:56:39.253 回答