简体   繁体   English

使用SQL Server创建一对多关系

[英]Create a one to many relationship using SQL Server

如何使用SQL Server创建一对多关系?

  1. Define two tables (example A and B), with their own primary key 使用自己的主键定义两个表(示例A和B)
  2. Define a column in Table A as having a Foreign key relationship based on the primary key of Table B 将表A中的列定义为具有基于表B的主键的外键关系

This means that Table A can have one or more records relating to a single record in Table B. 这意味着表A可以具有与表B中的单个记录相关的一个或多个记录。

If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint: 如果已经有表,请使用ALTER TABLE语句创建外键约束:

ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id) 
  • fk_b : Name of the foreign key constraint, must be unique to the database fk_b :外键约束的名称,对数据库必须是唯一的
  • b_id : Name of column in Table A you are creating the foreign key relationship on b_id :表A中要创建外键关系的列的名称
  • b : Name of table, in this case b b :表的名称,在本例中为b
  • id : Name of column in Table B id :表B中列的名称

This is a simple example of a classic Order example. 这是一个典型的Order示例的简单示例。 Each Customer can have multiple Order s, and each Order can consist of multiple OrderLine s. 每个客户可以有多个订单 ,每个订单可以包含多个OrderLine

You create a relation by adding a foreign key column. 您可以通过添加外键列来创建关系。 Each Order record has a CustomerID in it, that points to the ID of the Customer. 每个Order记录中都有一个CustomerID,它指向Customer的ID。 Similarly, each OrderLine has an OrderID value. 同样,每个OrderLine都有一个OrderID值。 This is how the database diagram looks: 这是数据库图的外观:

在此输入图像描述

In this diagram, there are actual foreign key constraints . 在此图中,存在实际的外键约束 They are optional, but they ensure integrity of your data. 它们是可选的,但它们可确保数据的完整性。 Also, they make the structure of your database clearer to anyone using it. 此外,它们使数据库的结构对使用它的任何人都更清晰。

I assume you know how to create the tables themselves. 我假设你知道如何自己创建表。 Then you just need to define the relationships between them. 然后你只需要定义它们之间的关系。 You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. 您当然可以在T-SQL中定义约束(由几个人发布),但也可以使用设计器轻松添加它们。 Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). 使用SQL Management Studio,您可以右键单击Order表,单击Design (我认为它可能在2005年被称为Edit)。 Then anywhere in the window that opens right-click and select Relationships . 然后在打开的窗口中的任意位置单击鼠标右键并选择“ 关系”

You will get another dialog, on the right there should be a grid view. 你会得到另一个对话框,右边应该有一个网格视图。 One of the first lines reads " Tables and Columns Specification ". 第一行中的一行是“ 表和列规范 ”。 Click that line, then click again on the little [...] button that appears on the right. 单击该行,然后再次单击右侧显示的小[...]按钮。 You will get this dialog: 你会得到这个对话框:

外键约束

The Order table should already be selected on the right. 应该已经在右侧选择了Order表。 Select the Customer table on the left dropdown. 选择左侧下拉列表中的Customer表。 Then in the left grid, select the ID column. 然后在左侧网格中,选择ID列。 In the right grid, select the CustomerID column. 在右侧网格中,选择CustomerID列。 Close the dialog, and the next. 关闭对话框,然后关闭对话框。 Press Ctrl+S to save. Ctrl + S保存。

Having this constraint will ensure that no Order records can exist without an accompanying Customer record. 拥有此约束将确保没有随附的客户记录就不能存在订单记录。

To effectively query a database like this, you might want to read up on JOINs . 要有效地查询这样的数据库,您可能需要阅读JOIN

This is how I usually do it (sql server). 这就是我通常的做法(sql server)。

Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
)
GO
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
GO
Insert into Master values('value')
--(1 row(s) affected)
GO
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4". 
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.

As you can see the second insert into the detail fails because of the foreign key. 正如您所看到的,由于外键,第二次插入细节失败。 Here's a good weblink that shows various syntax for defining FK during table creation or after. 这是一个很好的weblink,显示了在表创建过程中或之后定义FK的各种语法。

http://www.1keydata.com/sql/sql-foreign-key.html http://www.1keydata.com/sql/sql-foreign-key.html

If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. 如果你在谈论两种形式,比如老师和学生,你会为每个创建两个表,第三个用来存储这种关系。 This third table can have two columns, say teacherID and StudentId. 第三个表可以有两列,比如teacherID和StudentId。 If this is not what you are looking for, please elaborate your question. 如果这不是您要找的,请详细说明您的问题。

If you are not using SSMS then here is the syntax: 如果您不使用SSMS,那么这里是语法:

ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY 
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)

http://infogoal.com/sql/sql-add-foreignkey.htm http://infogoal.com/sql/sql-add-foreignkey.htm

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

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