2013-06-20 106 views
0

我有一個包含路由標識的公交車與公交車一臺bus_stops停止象下面這樣:MySQL的子查詢多個條件

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

我想同時包含停止1和停止2(用於停止1從站和停止2作爲對ROUTE_ID站我想獲得1234而不是「停止2從遊戲主板」和「停止1如要站」)

我寫此查詢:

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') 

但它返回r oute_id爲「stop1從站和stop2到站」和「stop2從站Staion和stop1到站」

謝謝。

+0

提供的表格結構沒有提到「from」和「to」工作站,但是你聲稱你現有查詢的問題是*它將「stop1作爲From station和stop2作爲To station」返回route_id,並且「stop2作爲從Staion和stop1作爲To Station」*。你如何區分「從」和「到」站? –

+0

@Mark我認爲他使用'sl_no',所以停止按順序:1,2,3 ...至少這是我認爲的 – Stephan

+0

是的,我正在使用sl_no進行排序... –

回答

0

如果我理解您的要求正確,你可以試試這個:

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

UPDATE:和並在爲了得到你想要的:

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 <> '' 
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