外鍵約束
自帶的引擎只有innoDB引擎支持外鍵,外鍵要求父表必須有對應列的索引,子表會自動建立索引 下面是兩個表country國家,字表citymysql
建立國家表
last_update語句的意思是時間戳不爲空,默認插入(第三條插入代表以實際插入數值爲準)和更新時間爲當前時間 primary key 有兩個做用,一是約束做用(constraint),用來規範一個存儲主鍵和惟一性,但同時也在此key上創建了一個主鍵索引sql
CREATE TABLE country( country_id INT UNSIGNED NOT NULL AUTO_INCREMENT, country VARCHAR(20), last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ONUPDATE CURRENT_TIMESTAMP, PRIMARY KEY(country_id) ); INSERT INTO country VALUES(1,'china',NOW()); insert into country values(2,'japan',curdate()); insert into country values(3,'usa','2007-11-20 11:11:50'); mysql> select * from country; +------------+---------+---------------------+ | country_id | country | last_update | +------------+---------+---------------------+ | 1 | china | 2019-07-12 09:30:16 | | 2 | japan | 2019-07-12 00:00:00 | | 3 | usa | 2007-11-20 11:11:50 | +------------+---------+---------------------+ 3 rows in set (0.00 sec
建立城市表
KEY idx_fk_coutry_id (country_id) country_id爲索引,能夠不要,由於建立外鍵會建立該列的索引 添加外鍵的語句:建立約束fk_city_country,外鍵 FOREIGN KEY 所在列是本表country_id,級聯REFERENCES的是表country的country_id列,country表不能單獨刪除,級聯更新spa
CREATE TABLE city( city_id INT UNSIGNED NOT NULL auto_increment, city VARCHAR(20) NOT NULL, last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, country_id INT UNSIGNED NOT NULL, PRIMARY KEY (city_id), KEY idx_fk_coutry_id (country_id), CONSTRAINT fk_city_country FOREIGN KEY (country_id) REFERENCES country (country_id) ON DELETE RESTRICT ON UPDATE CASCADE )ENGINE=INNODB default CHARSET=UTF8; INSERT INTO city values(1,'nanjing',NOW(),1); mysql> select * from city; +---------+---------+---------------------+------------+ | city_id | city | last_update | country_id | +---------+---------+---------------------+------------+ | 1 | nanjing | 2019-07-12 09:32:28 | 1 | +---------+---------+---------------------+------------+ 1 row in set (0.00 sec)
更新外鍵和刪除操做
#更新country mysql> update country set country_id=2 where country_id=1; Query OK, 1 row affected (0.05 sec) #更新後查詢,city級聯更新 mysql> select * from country; +------------+---------+---------------------+ | country_id | country | last_update | +------------+---------+---------------------+ | 2 | japan | 2019-07-12 00:00:00 | | 3 | usa | 2007-11-20 11:11:50 | | 10 | china | 2019-07-12 09:34:32 | +------------+---------+---------------------+ 3 rows in set (0.00 sec) mysql> select * from city; +---------+---------+---------------------+------------+ | city_id | city | last_update | country_id | +---------+---------+---------------------+------------+ | 1 | nanjing | 2019-07-12 09:32:28 | 10 | +---------+---------+---------------------+------------+ 1 row in set (0.00 sec) #刪除city mysql> delete from country where country_id=1; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`city`, CONSTRAINT `fk_city_country` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`) ON DELETE RESTRICT ON UPDATE CA SCADE)