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;
【编辑推荐】