Mysql在第二次连接时使用Join作为别名

时间:2015-05-22 19:36:33

标签: mysql join

我需要比较第一个Join到第二个的值..

SELECT d.* FROM nt_schedule d 
JOIN (SELECT DISTINCT schedule_id, locality, key_position 
        FROM nt_schedule_stops 
        WHERE locality = 'Greece') AS getit 
    USING (schedule_id)
JOIN (SELECT DISTINCT schedule_id, locality, key_position 
        FROM nt_schedule_stops 
        WHERE locality = 'London' AND !!key_position>getit.key_position!!` `) AS sendit 
    USING (schedule_id)
GROUP BY schedule_id`

这可能吗?

2 个答案:

答案 0 :(得分:1)

SELECT d.* 
FROM nt_schedule d 
JOIN (
  SELECT DISTINCT schedule_id, locality, key_position 
  FROM nt_schedule_stops 
  WHERE locality = 'Greece') AS getit 
ON getit.schedule_id = d.schedule_id
JOIN (
  SELECT DISTINCT schedule_id, locality, key_position 
  FROM nt_schedule_stops 
  WHERE locality = 'London' 
  ) AS sendit 
ON sendit.schedule_id = d.schedule_id
  AND sendit.key_position > getit.key_position
GROUP BY schedule_id

答案 1 :(得分:0)

找到一个可行的解决方案,不知道它是否是最快的..

JOIN (SELECT DISTINCT schedule_id, locality, key_position FROM nt_schedule_stops WHERE locality = 'Greece' AND key_position>(SELECT key_position FROM nt_schedule_stops WHERE locality = 'London'))