SQL Multiple Tables连接一对多关系

时间:2014-01-02 15:52:26

标签: mysql sql join

您好我有3张表

1)表路线

route_id
route_name
total_stop

2)表停止

stop_id
stop_name
stop_address
stop_latitude
stop_longitude

3)表route_stop

route_id
stop_id
stop_position

我的查询

SELECT 
  routes.route_name,
  (SELECT 
    CONCAT(
      stops.stop_latitude,
      ",",
      stops.stop_longitude
    ) 
  FROM
    stops 
  WHERE stops.stop_id = route_stop.stop_id 
    AND route_stop.stop_position = 1) AS start_pt,
  (SELECT 
    CONCAT(
      stops.stop_latitude,
      ",",
      stops.stop_longitude
    ) 
  FROM
    stops 
  WHERE stops.stop_id = route_stop.stop_id 
    AND route_stop.stop_position = routes.total_stop) AS end_pt,
  routes.total_stop 
FROM
  routes 
  INNER JOIN route_stop 
    ON routes.route_id = route_stop.route_id 
  INNER JOIN stops 
    ON route_stop.stop_id = stops.stop_id 
GROUP BY routes.route_id ;

这里end_pt列返回NULL,我在这里做错了什么。请帮帮....

编辑:表格结构+数据,SQL FILE

2 个答案:

答案 0 :(得分:2)

请尝试此查询

SELECT routes.route_name,
       CONCAT(startstop.stop_latitude,",",startstop.stop_longitude) as start_pt,
       CONCAT(endstop.stop_latitude,",",endstop.stop_longitude) as end_pt,
       routes.total_stop
FROM routes
INNER JOIN route_stop as routestart ON (routestart.route_id=routes.route_id AND routestart.stop_position = 1)
INNER JOIN route_stop as routeend ON (routeend.route_id=routes.route_id AND routeend.stop_position = routes.total_stop)
INNER JOIN stops as startstop ON (startstop.stop_id=routestart.stop_id)
INNER JOIN stops as endstop ON (endstop.stop_id=routeend.stop_id)

答案 1 :(得分:0)

您可以尝试此查询:

SELECT routes.route_id,routes.route_name, starts.start_pt, ends.end_pt, routes.total_stop
FROM routes
JOIN route_stop ON routes.route_id = route_stop.route_id
JOIN (
    SELECT stops.stop_id,CONCAT(stops.stop_latitude,",",stops.stop_longitude) as start_pt
    FROM stops
    JOIN route_stop ON stops.stop_id = route_stop.stop_id
    WHERE route_stop.stop_position = 1
) as starts ON starts.stop_id = route_stop.stop_id
JOIN (
    SELECT stops.stop_id,CONCAT(stops.stop_latitude,",",stops.stop_longitude) as end_pt
    FROM stops
    JOIN route_stop ON stops.stop_id = route_stop.stop_id
    JOIN routes ON routes.route_id = route_stop.route_id
    WHERE route_stop.stop_position = routes.total_stops
) as ends ON ends.stop_id = route_stop.stop_id