[英]Create a table with relationships SQL
I would like to know how relationships between tables are created.我想知道如何创建表之间的关系。
I intend that when a new row is added to table1 that row is also created in table 2, how can I do this?我打算将新行添加到 table1 时,该行也在表 2 中创建,我该怎么做?
Table1
ID_Orders ID_Line Orders Clients
1 2 A ABC
2 2 B ABC
Table2
ID_Orders ID_Line Product
1 2 A
2 2 B
I tried to use the foreign key relationship, but it is not working.我尝试使用外键关系,但它不起作用。
CREATE TABLE Table2(
ID_Orders int ,
ID_Line int,
Product text,
FOREIGN KEY(ID_Orders) REFERENCES Table1(ID_Orders),
FOREIGN KEY(ID_Line) REFERENCES Table1(ID_Line)
);
What you have described is not a standard relationship between two tables.您所描述的不是两个表之间的标准关系。 Those relationships are described using foreign key relationships.
这些关系使用外键关系来描述。 But you want "automatic" updates.
但是你想要“自动”更新。
The simplest method is to use a view:最简单的方法是使用视图:
create view table2 as
select ID_Orders, ID_Line, Orders as Product
from table1;
A variant on this is a materialized view , which would materialize the data, so queries might be faster (well, probably not in this case, but possibly if the query were more complicated).对此的一个变体是物化视图,它将物化数据,因此查询可能会更快(好吧,在这种情况下可能不是,但如果查询更复杂,则可能)。
An alternative is to have a bona fide table2
and using an insert
(and perhaps update
and delete
triggers as well) on table1
.另一种方法是拥有一个真正的
table2
并在table1
上使用insert
(也许还有update
和delete
触发器)。 When a row is inserted into table1
then the trigger can copy data to table2
.当将一行插入
table1
时,触发器可以将数据复制到table2
。
All that said, it is a bad practice to store the same data in multiple places.综上所述,将相同的数据存储在多个位置是一种不好的做法。 Sometimes, it can be an important optimization.
有时,它可能是一个重要的优化。 But from what you describe, you don't need two tables.
但是根据您的描述,您不需要两张桌子。
I know it's the most lazy way but it worked:) thanks我知道这是最懒惰的方式,但它奏效了:) 谢谢
SQL Management Studio Select Script... Create to... New Query Window. SQL Management Studio Select 脚本... 创建到... 新查询 Window。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.