【问题标题】:SQL: Join two different rows from the same table to a relationSQL:将同一表中的两个不同行连接到关系
【发布时间】:2014-10-19 14:25:08
【问题描述】:

假设我有一个名为 relation 的表,其中包含以下字段:

id, type, person1.id, person2.id

然后是带有此字段的名为person 的人的表:

id, name

现在我想创建一个包含以下信息的列表:

relation.id, relation.type, person1.id, person1.name, person2.id, person2.name

如何使用 SQL 语句实现这一点?我知道这可能是一个非常基本的问题。 :-(

【问题讨论】:

  • 我不明白你的意思,请完整显示表结构及其类型。
  • person 桌子上的钥匙是什么? name旁边还有一栏吗?
  • @wolφi 是的,两张桌子上都有一个id。我已经编辑了我的问题。
  • @HaroldL.Brown 那么编写自己的这两个表的连接的问题在哪里?
  • @HaroldL.Brown 未来的问题请阅读this

标签: sql oracle join subquery where


【解决方案1】:
select relation.type,a.Person1_name,b.person2.name  from relation inner join 

(select relation.type, person1.name Person1_name from relation  inner join person
on relation.person1=person.name
where person1 is not null)a
on relation.type=a.type
inner join 
(
select relation.type, person2.name,from relation  inner join person
on relation.person2=person.name
where person2 is not null)b
on relation.type=a.type

请试试这个代码

【讨论】:

    【解决方案2】:

    你需要使用 person 表两次:

    select rel.id, rel.type, p1.id, p1.name, p2.id, p2.name
      from relation rel
         , person p1
         , person p2
     where rel.person1 = p1.id
       and rel.person2 = p2.id
    

    看看this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-08
      • 2014-09-01
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 2021-03-20
      • 2017-02-20
      相关资源
      最近更新 更多