MySQL外键关联问题


继续再看老师给推荐的深入浅出mysql数据库开发这本书(下载见  ),看到innodb数据库的外键关联问题时,遇到了一个问题,书上写的是可以对父表进行修改,从而同步到子表的外键上去,可是自己的实验却是没有能够。

  1. mysql> show create table country\G  
  2. *************************** 1. row ***************************  
  3.        Table: country  
  4. Create Table: CREATE TABLE `country` (  
  5.   `country_id` smallint(5) unsigned NOT NULL auto_increment,  
  6.   `country` varchar(50) NOT NULL,  
  7.   `last_update` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,  
  8.   PRIMARY KEY  (`country_id`)  
  9. ENGINE=InnoDB DEFAULT CHARSET=utf8  
  10. 1 row in set (0.01 sec)  
  11.   
  12. mysql> show create table city\G  
  13. *************************** 1. row ***************************  
  14.        Table: city  
  15. Create Table: CREATE TABLE `city` (  
  16.   `city_id` smallint(5) unsigned NOT NULL auto_increment,  
  17.   `city` varchar(50) NOT NULL,  
  18.   `country_id` smallint(5) unsigned NOT NULL,  
  19.   `last_update` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,  
  20.   PRIMARY KEY  (`city_id`),  
  21.   KEY `country_id` (`country_id`),  
  22.   CONSTRAINT `city_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`)  
  23. ENGINE=InnoDB DEFAULT CHARSET=utf8  
  24. 1 row in set (0.00 sec)  
  25. mysql> select * from city;  
  26. +---------+----------+------------+---------------------+  
  27. | city_id | city     | country_id | last_update         |  
  28. +---------+----------+------------+---------------------+  
  29. |       1 | hancheng |          1 | 2012-01-09 09:18:33 |  
  30. +---------+----------+------------+---------------------+  
  31. 1 row in set (0.01 sec)  
  32.   
  33. mysql> select * from country;  
  34. +------------+---------+---------------------+  
  35. | country_id | country | last_update         |  
  36. +------------+---------+---------------------+  
  37. |          1 | chen    | 2012-01-09 09:16:38 |  
  38. +------------+---------+---------------------+  
 
  1. mysql> update country set country_id=100 where country_id=1;  
  2. ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test/city`, CONSTRAINT `city_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`))  

上面的问题是说因为有关联的存在,所以无法改变country_id这个字段。

  • 1
  • 2
  • 下一页

相关内容