SQL入門 5 表的設計 主鍵 外來鍵

2021-06-25 12:35:29 字數 2106 閱讀 5262

定義主鍵約束(每乙個表必須有乙個主鍵列)

create table student

(id int  primary key,

name varchar(40)

);定義主鍵自動增長

create table student

(id int  primary key auto_increment,

name varchar(40)

);定義唯一約束

drop table student;

create table student

(id int primary key auto_increment,

name varchar(40) unique

);定義非空約束

drop table student;

create table student

(id int primary key auto_increment,

name varchar(40) unique not null

);定義外來鍵約束

create table husband

(id int primary key,

name varchar(40)

);create table wife

(id int primary key,

name varchar(40),

husband_id int,

constraint husband_id_fk foreign key(husband_id) references husband(id)

);一對多或多對一的物件存到資料庫時,表的設計方案

部門和員工

create table department

(id int primary key,

name varchar(40)

);create table employee

(id int primary key,

name varchar(40),

salary decimal(8,2),

department_id int,

constraint department_id_fk foreign key(department_id) references department(id)

);多對多物件的表的設計(老師和學生)

create table teacher

(id int primary key,

name varchar(40),

salary decimal(8,2)

);create table student

(id int primary key,

name varchar(40)

);create table teacher_student

(teacher_id int,

student_id int,

primary key(teacher_id,student_id),

constraint teacher_id_fk foreign key(teacher_id) references teacher(id),

constraint student_id_fk foreign key(student_id) references student(id)

);一對一的物件的資料庫設計

create table person

(id int primary key,

name varchar(40)

);create table idcard

(id int primary key,

city varchar(40),

constraint id_fk foreign key(id) references person(id)

);自連線的表

create table person

(id int primary key,

name varchar(40),

parent_id int,

constraint parent_id_fk foreign key(parent_id) references person(id)

);

sql 主鍵表與外來鍵表的區分

主鍵 表和外建表是相對來說的,簡單的說就是乙個表的 主鍵是另外一張表的外來鍵。例如class 班級表主要字段如下 classid primary key 主鍵 班級id classname 班級名稱 studen 學生表主要字段如下 stuid primary key 主鍵 學生id stuname...

SQL主鍵表與外來鍵表的區分

主鍵 表和外建表是相對來說的,簡單的說就是乙個表的 主鍵是另外一張表的 外來鍵。例如 class 班級表主要字段如下 classid primary key 主鍵 班級id classname 班級名稱 studen 學生表主要字段如下 stuid primary key 主鍵 學生id stuna...

查詢表主鍵外來鍵資訊的SQL

oracle select o.obj as objectid,o.name as tablename,oc.name as constraintname,decode c.type 1,c 2,p 3,u 4,r 5,v 6,o 7,c as constrainttype,col.name as ...