使用 SQL Server 创建一对多关系 [英] Create a one to many relationship using SQL Server

查看:83
本文介绍了使用 SQL Server 创建一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you create a one to many relationship using SQL Server?

推荐答案

  1. 定义两个表(例如 A 和 B),使用它们自己的主键
  2. 将表 A 中的列定义为具有基于表 B 主键的外键关系

这意味着表 A 可以有一个或多个记录与表 B 中的单个记录相关.

This means that Table A can have one or more records relating to a single record in Table B.

如果您已经有了这些表,请使用 ALTER TABLE 语句来创建外键约束:

If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:

ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id) 

  • fk_b:外键约束的名称,必须是数据库唯一的
  • b_id:表 A 中您要在其上创建外键关系的列的名称
  • b:表名,在本例中为 b
  • id:表B中的列名
    • fk_b: Name of the foreign key constraint, must be unique to the database
    • b_id: Name of column in Table A you are creating the foreign key relationship on
    • b: Name of table, in this case b
    • id: Name of column in Table B
    • 这篇关于使用 SQL Server 创建一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆