获取ON子句中值为“x”的行的ID

时间:2014-08-07 21:18:12

标签: mysql

SELECT DISTINCT(journey.id), journey.departure
FROM journey
JOIN journey_day ON journey_day.journey = journey.id
JOIN pattern ON pattern.id = journey.pattern
JOIN pattern_link ON pattern_link.section = pattern.section
WHERE pattern.service = :service AND pattern.direction = :direction AND journey_day.day = :day
GROUP BY journey.id
HAVING SUM(pattern_link.from_stop = :arrival) > 0 and
       SUM(pattern_link.from_stop = :departure) > 0
ORDER BY journey.departure

上面我有一个相对简单的MySQL查询。

如何更改pattern_link表的上述连接,以便有效地执行以下操作:

“加入模式的部分等于pattern_link的部分(目前它做了什么),以及ID小于具有值”duck“的ID的行的位置

我不知道该怎么做的是“ID小于ID的行,其值为”duck“。如何在pattern_link join上执行此操作?它'如果它是一个特定的ID,我可以说ON id = 4,但我需要先得到鸭子的ID,所以我不确定。

由于

1 个答案:

答案 0 :(得分:0)

你可以做两种方式,更简单:

  SELECT j.id, j.departure
    FROM journey j
    JOIN journey_day jd 
      ON jd.journey = j.id
     AND jd.day = :day
    JOIN pattern p
      ON p.id = j.pattern
     AND p.direction = :direction 
     AND p.service = :service
    JOIN pattern_link pl 
      ON pl.section = p.section
     AND pl.id < (SELECT id FROM pattern_link WHERE value = 'duck')
GROUP BY j.id
  HAVING SUM(pl.from_stop = :arrival) > 0
     AND SUM(pl.from_stop = :departure) > 0
ORDER BY j.departure

或者(几乎可以肯定)更快:

  SELECT j.id, j.departure
    FROM journey j
    JOIN journey_day jd 
      ON jd.journey = j.id
     AND jd.day = :day
    JOIN pattern p
      ON p.id = j.pattern
     AND p.direction = :direction 
     AND p.service = :service
    JOIN pattern_link pl 
      ON pl.section = p.section
    JOIN pattern_link pl_duck
      ON pl_duck.id > pl.id
     AND pl_duck.value = 'duck'
GROUP BY j.id
  HAVING SUM(pl.from_stop = :arrival) > 0
     AND SUM(pl.from_stop = :departure) > 0
ORDER BY j.departure

请注意;我移除了DISTINCT,因为它被GROUP BY否定,并为我自己的偏好/理解添加了别名。

我还将表中的特定条件放在JOIN中尽我所能。