Mysql外鍵用法是Mysql數據庫中的基礎知識,下面就為您詳細將介紹Mysql外鍵用法,如果您對此方面有興趣的話,不妨一看。
昨晚用Mysql建外鍵約束,始終沒有成功,今天找到這個,原來只有InnoDB類型的表才可以使用Mysql外鍵.
只有InnoDB類型的表才可以使用外鍵
- CREATE TABLE person (
- id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
- name CHAR(60) NOT NULL,
- PRIMARY KEY (id)
- )type=innoDB;
- CREATE TABLE shirt (
- id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
- style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
- color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
- owner SMALLINT UNSIGNED NOT NULL,
- FOREIGN KEY (owner) REFERENCES PERSON(id)
- ON DELETE CASCADE
- ON UPDATE CASCADE,
- PRIMARY KEY (id)
- )type=innoDB;
然後打開MySQL Administrator終於看到 FOREIGN KEY有東西了,嘗試手工刪除後再用MySQL Administrator建立,成功。
- INSERT INTO person VALUES (NULL, 'Antonio Paz');
- SELECT @last := LAST_INSERT_ID();
- INSERT INTO shirt VALUES
- (NULL, 'polo', 'blue', @last),
- (NULL, 'dress', 'white', @last),
- (NULL, 't-shirt', 'blue', @last);
- INSERT INTO person VALUES (NULL, 'Lilliana Angelovska');
- SELECT @last := LAST_INSERT_ID();
- INSERT INTO shirt VALUES
- (NULL, 'dress', 'orange', @last),
- (NULL, 'polo', 'red', @last),
- (NULL, 'dress', 'blue', @last),
- (NULL, 't-shirt', 'white', @last);
- SELECT * FROM person;
- SELECT * FROM shirt;
測試UPDATE關聯
- UPDATE PERSON SET id=3 WHERE id=1;
- SELECT * FROM shirt;
測試DELETE關鍵
- DELETE FROM PERSON WHERE id=3;
- SELECT * FROM shirt;
解讀MySQL數據庫產品定價新策略
帶您學習DB2字符集和MySql字符集
查看MySQL數據庫表的命令介紹
基於Hash算法的Mysql分表處理
MySQL定義外鍵的方法