如何从第2个表

时间:2015-08-18 10:38:05

标签: mysql sql join

数据库是关于公交车的,所以有三个表:

停止

 stop_id | stop_name
 --------------------
    1    | station_1
    2    | station_2
    3    | station_3

ROUTE

route_id | route_num
--------------------
1        | route_1
2        | route_2
3        | route_3

ROUTE_STOP

stop_id | route_id
------------------
1       | 1
2       | 1
1       | 2
3       | 2
1       | 3
2       | 3
3       | 3

所以第一条路线有1号和2号站点,第2条路线有1号和3号站点,而第3条路线有站点​​。

尝试通过station_1和station_3获取route_num

SELECT distinct(r.route_num) from STOP s
JOIN ROUTE_STOP rs 
ON s.stop_id = rs.stop_id
JOIN ROUTE_STOP r_s 
ON rs.stop_id = r_s.stop_id
JOIN ROUTE r 
ON rs.route_id = r.route_id 
WHERE s.stop_name='station_1' OR s.stop_name='station_3' 
AND rs.stop_id <> r_s.stop_id

,结果应该是route_2和route_3,但它不起作用。如果站之间没有路线,则应该没有结果。

如果两个电台之间没有路由,如何获得经过2个电台的route_num

2 个答案:

答案 0 :(得分:0)

您的查询应该是

SELECT r.route_num from route r
JOIN ROUTE_STOP rs 
ON r.route_id = rs.route_id
JOIN STOP s ON rs.stop_id = s.stop_id 
WHERE s.stop_name in ('station_1','station_3');

答案 1 :(得分:0)

执行此操作的一种方法是加入表并使用in子句与group byhaving count()来查找匹配的组,或者按route_num分组并使用用于过滤具有所需停靠点的组的子句:

-- query 1
SELECT r.route_num 
FROM ROUTE r
JOIN ROUTE_STOP rs ON r.route_id = rs.route_id
JOIN STOP s ON rs.stop_id = s.stop_id 
WHERE s.stop_name IN ('station_1','station_3')
GROUP BY r.route_num
HAVING COUNT(DISTINCT s.stop_id) = 2;

-- query 2
SELECT r.route_num 
FROM ROUTE r
JOIN ROUTE_STOP rs ON r.route_id = rs.route_id
JOIN STOP s ON rs.stop_id = s.stop_id 
GROUP BY r.route_num
HAVING (SUM(CASE WHEN s.stop_name = 'station_1' THEN 1 ELSE 0 END) = 1)
   AND (SUM(CASE WHEN s.stop_name = 'station_3' THEN 1 ELSE 0 END) = 1);

因为MySQL将布尔表达式计算为1或0,所以可以将上一个查询中的having子句减少为:

HAVING (SUM(s.stop_name = 'station_1') = 1)
   AND (SUM(s.stop_name = 'station_3') = 1);

两个查询都假设在路线中可能会多次停止(如果路线在同一站点开始和结束)。

Sample SQL Fiddle