重新排序数据库中的行

时间:2017-02-10 07:29:10

标签: sql database mariadb adminer

我需要更改数据库表中的行顺序。 我的表有4列7行。我需要重新排序这些行

pk_i_id int(10)    unsigned Auto Increment   
s_name             varchar(255) NULL     
s_heading          varchar(255) NULL     
s_order_type       varchar(10) NULL

在Adminer中,当我将pk_i_id值(数字)更改为其他内容时,我收到此错误...

Cannot delete or update a parent row: a foreign key constraint fails    (`database_name`.`oc_t_item_custom_attr_categories`, CONSTRAINT `oc_t_item_custom_attr_categories_ibfk_1` FOREIGN KEY (`fk_i_group_id`) REFERENCES `oc_t_item_custom_attr_groups` (`pk_i_id`))

你知道怎么改吗?谢谢

修改

oc_t_item_custom_attr_categories

 fk_i_group_id      int(10) unsigned     
 fk_i_category_id   int(10) unsigned    

索引

PRIMARY fk_i_group_id, fk_i_category_id
INDEX   fk_i_category_id 

外包钥匙

fk_i_group_id       oc_t_item_custom_attr_groups_2(pk_i_id) RESTRICT    RESTRICT    
fk_i_category_id    oc_t_category(pk_i_id)                  RESTRICT    RESTRICT    

1 个答案:

答案 0 :(得分:2)

您需要更改表database_nameoc_t_item_custom_attr_categories上的外键,以便它与引用的列一起更新。

ALTER TABLE database_name.oc_t_item_custom_attr_categories DROP CONSTRAINT oc_t_item_custom_attr_categories_ibfk_1;
ALTER TABLE database_name.oc_t_item_custom_attr_categories
  ADD CONSTRAINT oc_t_item_custom_attr_categories_ibfk_1 FOREIGN KEY (fk_i_group_id)
      REFERENCES oc_t_item_custom_attr_groups (pk_i_id)
      ON UPDATE CASCADE;

由于MariaDB在创建表后似乎不支持添加外键,因此假设表的描述正确,这就是它应该如何工作:

RENAME TABLE oc_t_item_custom_attr_categories TO oc_t_item_custom_attr_categories_2;

CREATE TABLE oc_t_item_custom_attr_categories (
  fk_i_group_id int(10) unsigned,
  fk_i_category_id int(10) unsigned,
  PRIMARY KEY(fk_i_group_id, fk_i_category_id),
  INDEX (fk_i_category_id),
  CONSTRAINT `oc_t_item_custom_attr_categories_ibfk_1` FOREIGN KEY (fk_i_group_id)
      REFERENCES oc_t_item_custom_attr_groups (pk_i_id)
      ON UPDATE CASCADE,
  CONSTRAINT `oc_t_item_custom_attr_categories_ibfk_2` FOREIGN KEY (fk_i_category_id)
      REFERENCES oc_t_category (pk_i_id)
) ENGINE = XtraDB; --change engine to what you are using

INSERT INTO oc_t_item_custom_attr_categories SELECT * FROM oc_t_item_custom_attr_categories_2;

它如何在MySQL数据库中的示例数据上运行:http://rextester.com/ZAKR50399