【问题标题】:Create view from 2 tables with one table precedence with other table (mostly both tables are similar except one col)从 2 个表创建视图,其中一个表优先于另一个表(除了一个列之外,两个表大部分都相似)
【发布时间】:2019-08-10 11:30:54
【问题描述】:

从 2 个表创建视图,其中一个表优先于另一个表(除了一个列之外,大多数表都相似)。

需要 2 个表的视图。

Table1 table contains below columns with values:
ValueOne = C11
ValueTwo= C12
ValueThree= C13

Table2 table contains below columns (extra id column compare to table1).   
Id = 123   
ValueOne = C11  
ValueTwo= V12  
ValueThree= C13

Table2 优先于 Table1。当 w 使用 ID 查询时,如果 Id 不存在,则必须从 Table1 中选择值。如果 Id 可用,则必须从 Table2 中选择值。

为此,我需要一个视图来组合这两个表,当我们从视图中查询时,我们需要得到正确的结果。

example: 1) Select * from ViewName where ID=123
 then in this case I have to get below values (from table2, as the ID exist in the table2):   
 Id = 123   
ValueOne = C11   
ValueTwo= V12   
ValueThree= C13   

2) Select * from ViewName where ID=01
in this case it has to get the below values (Id and other values from Table1, 
as ID is not there in Table2:   
     Id = 01   
    ValueOne = C11    
    ValueTwo= C12   
    ValueThree= C13

【问题讨论】:

  • 包含两个表的视图假定某种连接。如果这些表以某种方式相关,那是有道理的。我看不到这两个表之间有任何关系,所以我不知道如何创建一个视图以便它返回所需的数据。此外,ID = 01 是从哪里来的?它在您的示例表中不存在。
  • @Littlefoot,任何其他方法也可以(而不是视图有什么方法可以创建它)

标签: sql oracle join view


【解决方案1】:

您将需要使用联接。像这样的东西应该可以工作

    CREATE VIEW View_1 AS
    select t2.*
    from Table2 t2

    Union ALL

    Select t1.*
    from table1 t1 
    LEFT JOIN Table2 t2 on t1.ID = t2.ID 
    where t2.ID is NULL

我没有测试,但这应该会给你一个好的开始。

【讨论】:

  • table1中没有ID。那么我们可以在什么基础上加入表格(你提到的 t1.id=t2.id)?
  • 这就是你应该告诉我们的。
  • @Littlefoot,希望我在我的问题中提到过(第二张表类似于第一张表,只有一个额外的列,即 ID)。
  • @Gordon Linoff 对此有何帮助。
  • 如果您不知道如何加入这些表格(顺便说一句,您没有阅读我在问题下方发布的评论吗?),我们应该怎么知道呢?所以 - 在我看来 - 不:你提到还不够。
猜你喜欢
  • 2021-12-16
  • 1970-01-01
  • 2016-08-31
  • 2021-09-17
  • 2018-06-20
  • 2014-12-26
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多