如何通过SQL获取这两个郊区?

时间:2011-04-28 06:22:53

标签: mysql sql join

我希望在我的SQL中获得一个出发地和目的地郊区。

SELECT jp.`id`,
     CONCAT(u.`first_name`, " ", u.`last_name`) AS `name`,
     jp.`departure_time`,
     jp.`destination_time`,
     s.`suburb` AS `departure_suburb`


FROM `journey_planning` AS `jp`
JOIN `users` AS `u` ON jp.`driver_id` = u.`id`
JOIN `suburbs` AS s ON jp.`departure_suburb_id` = s.`id`
  OR jp.`destination_suburb_id` = s.`id`

如您所见,有一个departure_suburb_iddestination_suburb_id。我需要它们映射到suburbs表中的相对值。

此刻,这将返回两行,除了不同的郊区名称外,两行都有相同的信息(但显然都是departure_suburb。)

我不是SQL专家,所以我不确定我应该做什么。我考虑过使用子查询,但我认为没有它们可能有一种方法可以避免两次查找。

虽然departure_suburbdestination_suburb指向suburbs表中的正确值,但我应该如何修改此查询以返回现在的状态?

3 个答案:

答案 0 :(得分:3)

您需要两次加入郊区表,一次是出发,一次是目的地。即使隐含“INNER JOIN”,也可以输入您正在使用的联接类型,这也是一个好习惯!

SELECT jp.`id`,
     CONCAT(u.`first_name`, " ", u.`last_name`) AS `name`,
     jp.`departure_time`,
     jp.`destination_time`,
     s.`suburb` AS `departure_suburb`
     s2.`suburb` AS `destination_suburb` 

FROM `journey_planning` AS `jp`
JOIN `users` AS `u` ON jp.`driver_id` = u.`id`
JOIN `suburbs` AS s ON jp.`departure_suburb_id` = s.`id`
JOIN `suburbs` AS s2 ON jp.`destination_suburb_id` = s2.`id`

答案 1 :(得分:1)

SELECT
    jp.id
  , CONCAT(u.first_name, " ", u.last_name) AS name
  , jp.departure_time
  , jp.destination_time
  , dep.suburb AS departure_suburb
  , dest.suburb AS destination_suburb

FROM journey_planning AS jp
  JOIN users AS u 
    ON jp.driver_id = u.id
  JOIN suburbs AS dep 
    ON jp.departure_suburb_id = dep.id
  JOIN suburbs AS dest 
    OR jp.destination_suburb_id = dest.id

怎么可以这样做呢? (对于像你这样的简单JOIN的查询,我不建议这样做)。由于jp表上的所有关系都是1对多,因此可以这样做:

SELECT
    jp.id
  , CONCAT( ( SELECT first_name
              FROM users
              WHERE jp.driver_id = users.id
            )
          , " "
          , ( SELECT last_name
              FROM users
              WHERE jp.driver_id = users.id
            )
          )
      AS name
  , jp.departure_time
  , jp.destination_time
  , ( SELECT suburb
      FROM suburbs
      WHERE jp.departure_suburb_id = suburbs.id
    ) 
      AS departure_suburb
  , ( SELECT suburb
      FROM suburbs
      WHERE jp.destination_suburb_id = suburbs.id
    ) 
      AS destination_suburb

FROM journey_planning AS jp

正如您所看到的,它变得非常复杂,尤其是当您想要从表中显示多个字段时,例如表用户的名字和姓氏。

答案 2 :(得分:0)

使用不同的表别名再次加入郊区:

SELECT jp.`id`,
    CONCAT(u.`first_name`, " ", u.`last_name`) AS `name`,
    jp.`departure_time`,
    jp.`destination_time`,
    departure_suburb.`suburb` AS `departure_suburb`,
    destination_suburb.`suburb` AS `destination_suburb`
FROM `journey_planning` AS `jp`
    JOIN `users` AS `u` ON jp.`driver_id` = u.`id`
    JOIN `suburbs` AS depart_suburb ON jp.`departure_suburb_id` = s.`id`
    JOIN `suburbs` AS destination_suburb ON jp.`destination_suburb_id` = ss.`id`