SQL中的业务逻辑关系

问题描述

| 谁能告诉我在sql(Server)中的表之间如何建立一种“ 0”和“ 1”关系? 非常感谢你。     

解决方法

1比1 .. * 创建从父表到子级主键(查找表)的外键。
CREATE TABLE  A
(
   id int NOT NULL IDENTITY(1,1) PRIMARY KEY,Somecolumn int,SomeOtherColumn Varchar(50),B_id int CONSTRAINT FOREIGN KEY REFERENCES B(id),-- ...other columns
)

CREATE TABLE  B
(
   id int NOT NULL IDENTITY(1,Name Varchar(50)
)
1至0..1 使用主键也定义为父表的外键创建表
CREATE TABLE  [Master]
(
   id int NOT NULL IDENTITY(1,-- ...other columns
)

CREATE TABLE [Child]
(
   id int NOT NULL PRIMARY KEY,OtherColumn Varchar(50),)

ALTER TABLE Child
   ADD  CONSTRAINT FK_Master FOREIGN KEY (id) REFERENCES Master(id)
    ,一对多 定义两个具有各自主键的表(示例A和B) 基于表B的主键将表A中的列定义为具有外键关系 这意味着表A可以具有一个或多个与表B中的单个记录相关的记录。 如果您已经有表,请使用ALTER TABLE语句创建外键约束: 更改表添加约束外键fk_b(b_id)引用b(id)
* 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