简体   繁体   English

如何在四个表上应用左外部联接条件?

[英]How can i apply left outer join conditions on four tables?

i was trying to apply joins on 4 tables. 我试图在4个表上应用联接。 but i could not find proper result for that. 但是我找不到合适的结果。 i have 4 tables like 1.students,2.college,3.locations,4.departments. 我有4个表格,例如1.students,2.college,3.locations,4.departments。 so i have same column sid in all tables which can be used to join conditions. 所以我在所有表中都可以使用相同的列sid来加入条件。 i want all matched rows from four tables as mentioned columns in select statement below and unmatched rows in left table which is left outer join work. 我想要四个表中所有匹配的行,如下面的select语句中提到的列,左表中不匹配的行是外部连接工作。

i have tried this syntax. 我已经尝试过这种语法。

select 
  students.sname,
  college.cname,
  locations.loc,
  department.dept 
from students, college, locaions, departments 
where student.sid=college.sid(+) 
and college.sid=locations.sid(+) 
and locations.sid=department.sid(+);

is this right ? 这是正确的吗 ?

This is an old-fashioned way of outer-joining in an Oracle database. 这是在Oracle数据库中进行外部联接的老式方法。 For Oracle this statement is correct; 对于Oracle,此声明是正确的; in other DBMS it is invalid. 在其他DBMS中,它是无效的。

Anyway, nowadays (as of Oracle 9i; in other DBMS much longer) you should use standard SQL joins instead. 无论如何,如今(从Oracle 9i开始;在其他DBMS中则更长),您应该改为使用标准SQL连接。

select 
  s.sname,
  c.cname,
  l.loc,
  d.dept 
from students s
left outer join college c on c.sid = s.sid
left outer join locations l on l.sid = c.sid
left outer join departments d on d.sid = l.sid;

Given what you've shown it would appear that what you really want is 鉴于您所显示的,您似乎真正想要的是

select s.sname,
       c.cname,
       l.loc,
       d.dept 
from students s
LEFT OUTER JOIN college c
  ON c.SID = s.SID
LEFT OUTER JOIN locations l
  ON l.SID = s.SID
LEFT OUTER JOIN departments d 
  ON d.SID = s.SID

The issue in your original query is that because an OUTER JOIN is an optional join, you can end up with NULL values being returned in one of the join fields, which then prevents any of the downstream values being joined. 原始查询中的问题是,由于OUTER JOIN是可选联接,因此最终可能会在其中一个联接字段中返回NULL值,这将阻止任何下游值联接。 I agree with @ThorstenKettner who observes in a comment that SID is apparently a "student ID", but it's not reasonable or appropriate to have a "student ID" field on tables named COLLEGE, LOCATIONS, or DEPARTMENTS. 我同意@ThorstenKettner的意见,他在评论中指出SID显然是“学生证”,但在名为COLLEGE,LOCATIONS或DEPARTMENTS的表上具有“学生证”字段是不合理或不适当的。 Perhaps you need to update your design to allow any number of students to be associated with one of these entities, perhaps using a "join" table. 也许您需要更新设计,以允许任何数量的学生与这些实体之一相关联,也许使用“联接”表。

Best of luck. 祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM