深入mysql外來鍵關聯問題的詳解(中)

2021-06-27 14:07:26 字數 1186 閱讀 7839

**如下:

mysql> update country set country_id=100 where country_id=1;

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這個字段。 

然後自己又重新看了下書本,發現自己的sql語句中沒有innodb的外來鍵約束方式(cascade,set null,no action,restrict),感覺這就是自己出問題的地方。

可是怎麼加入關聯方式呢,上網找了好半天也沒有合適的方法。就自己找唄,就通過老師說的方法,? help一點兒一點兒終於找到了怎麼改變的方法,文件功能很強大啊

**如下:

add [index_name] [index_type] (index_col_name,...)

add [constraint [symbol]]

primary key [index_type] (index_col_name,...)

add [constraint [symbol]]

unique [index

key] [index_name] [index_type] (index_col_name,...)

寫了後又是一大堆的錯誤,無從下手啊 

**如下:

mysql> alter table city add constraint `city_ibfk_1` foreign key (`country_id`) references `country` (`country_id`) on update cascade;

error 1005 (hy000): can't create table '.\test\#sql-ed0_37.frm' (errno: 121)

zhouqian@zhou:~$ perror 121

os error code 121:  remote i/o error

mysql error code 121: duplicate key on write or update

關聯 外來鍵問題

外來鍵問題 外來鍵一定是每個表的主鍵關聯問題 兩個表之間有聯絡,是通過外來鍵的設定模型中如果有外來鍵和多對多字段,建立的時候外來鍵必須首先繫結,然後儲存,才能新增多對多字段。relationships 主要有三類 many to one,many to many,one to one class s...

mysql 外來鍵詳解 MySQL的外來鍵約束詳解

外來鍵的作用 主要作用有兩個,乙個保證資料的完整性和一致性,乙個是方便一些er圖生成工具生成更具可讀性的er圖。注意 引入外來鍵可能會導致效能下降 mysql中的外來鍵 mysql有兩種常用的引擎型別 myisam和innodb。目前只有innodb引擎型別支援外來鍵約束。innodb中外鍵約束定義...

MySQL 外來鍵關聯策略

eg.乙個使用者可有擁有多個訂單,乙個訂單只能屬於乙個使用者,一對多,在tb order中使用外來鍵user id關聯tb user的id。當刪除 更新tb user中的主鍵時,與之關聯的tb order要受到影響,比如 tb user中的一條記錄 1chy abcd tb order中一條記錄,1...