【问题标题】:SQL: How to join the same table multiple times?SQL:如何多次加入同一张表?
【发布时间】:2018-07-21 04:42:03
【问题描述】:

我有两个表,我需要为两个不同的列加入第二个表两次。表格格式如下:

表 1:trip_details

column            type
name              string
start_country_id  int
end_country_id    int

表 2:国家信息

column   type
id       int
country  string

我想获取名称、起始国家和结束国家。

这将是我的尝试:

SELECT
trip_details.name AS "Name",
country_info.country AS "Start Country",
country_info.country AS "End Country"

FROM
trip_details

LEFT JOIN country_info ON country_info.id = trip_details.start_country_id
LEFT JOIN country_info ON country_info.id = trip_details.end_country_id

据我所知,问题出在连接上,因为我在 Select 子句中使用了两次“country_info.country”。对于这些情况,最好的方法/做法是什么?

编辑:
不确定是否有其他方法可以做到这一点,但这只是我的 SQL 查询的一部分,所以我确实需要使用 LEFT JOIN

【问题讨论】:

  • this 问题非常相似。相隔仅半小时!
  • @HoneyBadger 为什么不呢?更多的是无穷无尽的未研究重复。
  • 嗨。下次请努力在谷歌上搜索您的问题,例如您当前的标题,这样您就不会再问另一个重复的问题了。另见minimal reproducible example

标签: mysql sql select join left-join


【解决方案1】:

拥有两个join 子句是正确的方法。您只是错过了给他们不同的别名以区分两者:

SELECT    td.name AS "Name",
          sci.country AS "Start Country",
          eci.country AS "End Country"
FROM      trip_details td
LEFT JOIN country_info sci ON sci.id = td.start_country_id
LEFT JOIN country_info eci ON eci.id = td.end_country_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 2021-06-16
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多