创建用于检查多个表中的数据的SQL视图

时间:2016-09-16 15:36:22

标签: sql-server view

所以我有一个sql表,它将保存一个像这样的ID

---------------------------------------------------
| RecordID | Date | Price
--------------------------------------------------
| 1 | 8/31/2016 | 49
--------------------------------------------------
| 2 | 8/31/2016 | 101
--------------------------------------------------

我还有3个其他表可以保存有关此ID的信息,并且可以包含不同数量的列

Table 1
---------------------------------------------------
| RecordID | Date | Price | Name
--------------------------------------------------
| 1 | 8/31/2016 | 50 | System
--------------------------------------------------
Table 2
---------------------------------------------------
| RecordID | Date | Price | Coupon
--------------------------------------------------
| 2 | 8/31/2016 | 100 | 7
--------------------------------------------------

但ID在它们之间分开。含义表1可以具有ID 1,然后表2可以具有ID 2,依此类推。 ID只能存在于三个表中的一个中。

所以我的愿望是创建一个视图,我可以从原始表中获取ID和价格,并找到此ID存在于哪个表中并将它们放在一起,就像这样

---------------------------------------------------
| RecordID | Date | Price1 | Price2
--------------------------------------------------
| 1 | 8/31/2016 | 49 | 50
--------------------------------------------------
| 2 | 8/31/2016 | 101 | 100
--------------------------------------------------

2 个答案:

答案 0 :(得分:1)

您可以使用[{ "id": 0, "value": "Lorem test Ipsuver since the 1500s,but also the leap into electronic typesetting, remaining essentially unchanged." }, { "id": 1, "value": "-19170aee171f a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged." }, { "id": 2, "value": "19-9de6-19170aee171f a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged." }, { "id": 3, "value": "ee171f a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged." }] LEFT OUTER JOINS

来执行此操作

假设您有一个名为coalesce的主表和另外3个名为tRecordstInfo1tInfo2的表,所有这些表都有tInfo3和{ {1}}列:

RecordID

答案 1 :(得分:0)

根据您在表格中的数据类型,考虑创建一个视图以合并其他3个表格的结果,以制作虚拟组合表:

create view vRecordCombo
select RecordId, Date, Price, Name as 'InfoString', NULL as 'InfoValue'
from table1
UNION ALL
select RecordId, Date, Price, NULL as 'InfoString', Coupon as 'InfoValue'
from table2

然后你可以对组合进行连接,好像它是包含所有记录的单个表。