Oracle SQL连接三个表

时间:2014-05-23 18:58:45

标签: sql oracle oracle10g left-join

我有三个表,我想要连接查询或与下面提到的结果相关

 Types ( Table One)
 -------
 typeId
 -------
 square
 circle
 triangle


 Sets ( Table Two)
 ------
 id setValue setName
 ------------------
 1    one      setOne
 2    two      setTwo
 3    three    setThree


 Formation ( Table Three ) Types and sets are foreign keys to the other tables
 ---------
 id setValue  types     extra   notes
 --------------------------------------
 1     two     circle     5       xyz
 2     three   square     4       abc

我想加入这个表并以这种方式得到结果,总是我应该得到输入的所有类型给出

如果用户选择设置值为“2”,则结果应为

 types      setValue        extra       notes
 --------------------------------------------
 square     null            null        null
 circle     two             5           xyz
 triangle   null            null        null

如果用户选择键入值为'square',则结果应为

  types     setValue        extra       notes
 --------------------------------------------
 square     three           4           abc
 circle     null            null        null
 triangle   null            null        null

如果假设用户选择设置值为'矩形',则结果应为

 types      setValue        extra       notes
--------------------------------------------
 square     null            null        null
 circle     null            null        null
 triangle   null            null        null

期待解决方案oracle 10g兼容代码

1 个答案:

答案 0 :(得分:0)

SELECT F.types, F.setValue, F.extra, F.notes
FROM types t
LEFT JOIN Formation F
 on t.typeID = F.Types
 AND ((F.SetValue = 'YourSetInput')
  OR (F.Types = 'YourTypesInput'))

通过使用左外连接,我们始终保留所有类型。通过在连接上设置限制标准而不是在where子句中,我们不必担心意外地排除您想要查看的空值。

然而,这确实有一个缺点,即如果两个setvalue和类型都被键入,则返回。这可能是也可能不是期望的结果,因为用例还没有被涵盖。

所以在回顾中

每次都返回所有表格,无论其他标准如何 然后从形成中返回匹配所选输入的类型或集合的条件。