-- 建立表的相關約束
主鍵約束 PRIMARY KEY (主鍵自帶索引 PK 關聯式資料庫領域,要求一個表只有一個主鍵)
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
tname VARCHAR(30)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- 複合主鍵 有一個重複 按另外一個排
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30),
PRIMARY KEY(tid,tname)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
SELECT * FROM t1;
-- 主鍵名 CONSTRAINT myhpk
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30),
CONSTRAINT myhpk PRIMARY KEY(tid)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE t1;
儲存引擎
MYISAM 速度快
INNODB 事務 外來鍵 (聯網售票,銀行轉賬業務,對事物要求高專案)
預設約束 DEFAULT ‘男’ DEFAULT 18
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30) NOT NULL COMMENT '老師姓名',
tage TINYINT UNSIGNED DEFAULT 18,-- 預設年齡
PRIMARY KEY(tid)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO t1(tname) VALUES('李老師');
DROP TABLE t1;
CREATE TABLE t1(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30) NOT NULL COMMENT '老師姓名',
tdate DATETIME DEFAULT NOW(),-- 當前時間
tage TINYINT UNSIGNED DEFAULT 18,-- 預設年齡
PRIMARY KEY(tid)
)ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
SELECT * FROM t1;
非空約束 NOT NULL
CHECK 約束(沒什麼卵用)
CREATE TABLE t1
(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(20),
tage TINYINT UNSIGNED,
CHECK (tage>18),
PRIMARY KEY(tid)
);
INSERT INTO t1 VALUES(NULL,'張三',2)
DROP TABLE t1;
外來鍵約束 FOREIGN KEY REFERENCES 要求使用外來鍵的表 必須是 INNODB 儲存引擎
-- 根據舊錶建立新表 複製結構 不復制內容
CREATE TABLE ttt LIKE student;
DROP TABLE job,s,t,student,ttt;
-- 外來鍵的使用
CREATE TABLE teacher
(
tid INT UNSIGNED NOT NULL AUTO_INCREMENT,
tname VARCHAR(30) NOT NULL,
KEY(tname),-- 建立表的時候,同時在tname列建立索引
PRIMARY KEY(tid)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO teacher VALUES(NULL,'張老師'),(NULL,'李老師'),(NULL,'趙老師');
SELECT * FROM teacher;
DROP TABLE teacher;
CREATE TABLE student
(
sid INT UNSIGNED NOT NULL AUTO_INCREMENT,
sname VARCHAR(30) NOT NULL,
tid INT UNSIGNED,
PRIMARY KEY(sid),
-- constraint fk foreign key(tid) references teacher(tid) -- 建立外來鍵 關聯到teacher表
-- constraint fk foreign key(tid) references teacher(tid) on delete cascade, 刪除與之關聯項
CONSTRAINT fk FOREIGN KEY(tid) REFERENCES teacher(tid) ON DELETE SET NULL, -- 刪除後,空的內容用null補上
)ENGINE=INNODB AUTO_INCREMENT=201601 DEFAULT CHARSET=utf8;
INSERT INTO student VALUES(NULL,'張三',1),(NULL,'趙六三',1),(NULL,'李四',2),(NULL,'王五',1)
SELECT * FROM student;