mysql子查询的多个条件

时间:2013-06-20 07:51:25

标签: mysql sql

我有一张表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 as From station and stop2 as to station”和“stop2 as From Staion and stop1 as To Station”

2 个答案:

答案 0 :(得分: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 <> ''

答案 1 :(得分: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