1. 程式人生 > >MySQL表rename導致的外鍵問題

MySQL表rename導致的外鍵問題

show constrain orm 表結構 tab 查看表 into problem arch

背景:
由於zabbix監控的問題圖形展示很慢,對zabbix 庫的events表進行了清理,清理過程采用了原表rename成bak表,重建events表後,將備份表部分數據導入到新表中。

後發現zabbix平臺無法報警,無法恢復報警,日誌類似報錯:
 2315:20190301:104933.609 [Z3005] query failed: [1452] Cannot add or update a child row: a foreign key constraint fails (`zabbix`.`event_recovery`, CONSTRAINT `c_event_recovery_1` FOREIGN KEY (`eventid`) REFERENCES `events_bak20190225` (`eventid`) ON DELETE CASCADE) [insert into event_recovery (eventid,r_eventid,correlationid,c_eventid,userid) values (4242559,4242581,null,null,null),(4242561,4242580,null,null,null),(4242447,4242580,null,null,null);

原來rename後,關聯的外鍵表的約束竟然一並修改成了歸檔表的關聯。
處理方法如下:
查看哪些表建立外鍵時關聯了歸檔表

select  distinct TABLE_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_SCHEMA  =‘zabbix‘ and CONSTRAINT_name != ‘PRIMARY‘ and REFERENCED_TABLE_NAME like ‘event%‘;
+----------------+--------------------+-----------------------+
| TABLE_NAME     | CONSTRAINT_NAME    | REFERENCED_TABLE_NAME |
+----------------+--------------------+-----------------------+
| acknowledges   | c_acknowledges_2   | events                |
| alerts         | c_alerts_2         | events                |
| alerts         | c_alerts_5         | events                |
| event_recovery | c_event_recovery_1 | events                |
| event_recovery | c_event_recovery_2 | events                |
| event_recovery | c_event_recovery_3 | events                |
| event_tag      | c_event_tag_1      | events_bak20190225    |
| problem        | c_problem_1        | events                |
| problem        | c_problem_2        | events                |
+----------------+--------------------+-----------------------+

查看表結構:

show create table event_tag\G
*************************** 1. row ***************************
       Table: event_tag
Create Table: CREATE TABLE `event_tag` (
  `eventtagid` bigint(20) unsigned NOT NULL,
  `eventid` bigint(20) unsigned NOT NULL,
  `tag` varchar(255) NOT NULL DEFAULT ‘‘,
  `value` varchar(255) NOT NULL DEFAULT ‘‘,
  PRIMARY KEY (`eventtagid`),
  KEY `event_tag_1` (`eventid`),
  CONSTRAINT `c_event_tag_1` FOREIGN KEY (`eventid`) REFERENCES `events_bak20190225` (`eventid`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

修改外鍵約束:

alter table event_tag drop FOREIGN KEY  c_event_tag_1;
alter table event_tag add FOREIGN KEY  c_event_tag_1 (`eventid`) REFERENCES `events`(`eventid`) ON DELETE CASCADE;

zabbix好多外鍵,下次清理數據直接刪除吧。

MySQL表rename導致的外鍵問題