【问题标题】:Query to join two tables by mapping third table without returning all records from third table in Oracle通过映射第三个表而不返回Oracle中第三个表的所有记录来查询连接两个表
【发布时间】:2015-06-08 15:45:24
【问题描述】:

我有 3 张桌子:

表Maths:

ID   Marks1
(1 ,    80)

表English:

ID   Marks2
(2 ,    85)

表Student:

ID    Name
(1 ,    Raj)
(2 ,    Sam)
(3 ,    John)

我需要一个 SQL 查询 (Oracle) 来获得以下输出:

ID Name Marks1 Marks2
(1 , Raj , 80 ,    (null))
(2 , Sam , (null) , 85)

我写的一些查询:

select B.ID, B.Name, A.Marks1, C.Marks2 from 
(select ID, Marks1 from Maths) A
full join Student B on B.ID=A.ID
left join (select ID, Marks2 from English) C
on C.ID=B.ID

但是这个查询会返回 Student 表中我不需要的所有记录。 我只需要数学和英语表中的记录。 请帮我解决这个问题。

【问题讨论】:

    标签: sql oracle join left-join


    【解决方案1】:

    您需要行,其中学生的 ID 至少出现在表 MATHS、ENGLISH 之一中。这些查询给出了你想要的输出:

    select id, s.name, m.Marks1, e.Marks2 
      from maths m 
        full join english e using (id)
        join student s using (id);
    

    ...或:

    select s.id, s.name, m.Marks1, e.Marks2 
      from student s
        left join english e on e.id=s.id
        left join maths m on m.id = s.id
      where e.id is not null or m.id is not null
    

    SQLFiddle demo

    在第一个查询中加入表的顺序很重要——这就是你得到不正确输出的原因。更多informations with examples关于加入。

    【讨论】:

    • 如何使用 'using' 子句连接到另一个维度表。例如,我有另一个表 Grade,列有grade_id、grade_name。考虑包含在英语和数学表中的grade_id 列。现在我想在我的结果集中检索grade_name。我该怎么做,请帮忙。
    • 我认为你需要用左连接两次加入这个额外的表,所以添加这一行:left join grade g1 on g1.grade_id = m.grade_id 和这一行:left join grade g2 on g2.grade_id = e.grade_id。请参阅附件SQLFiddle 以获取完整的新查询。
    【解决方案2】:

    只需将您的 FULL JOIN(完全外连接 - 在任一表中都有行时返回记录)更改为 JOIN(内连接 - 仅当行存在于两个表中时才连接)

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      相关资源
      最近更新 更多