0

I have created a table member_history_logs.

        CREATE TABLE `member_history_logs` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `element_id` int(11) NOT NULL,
          `status` varchar(1) DEFAULT NULL,
          `start_date` datetime NOT NULL,
          `end_date` datetime DEFAULT NULL,
          PRIMARY KEY (`id`),
          KEY `status` (`status`),
          KEY `element_id` (`element_id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=134 DEFAULT CHARSET=utf8;

There is another table named members consisting of

    'id', 'int(11)', 'NO', 'PRI', NULL, 'auto_increment'
    'description', 'varchar(100)', 'NO', '', NULL, ''
    'short_name', 'varchar(1)', 'YES', '', NULL, ''

I want to perform an alter table

alter table member_history_logs add foreign key (element_id) references members (id);

I am getting the following error:

Error Code:1452 cannot add or update a child row a foreign key constraint fails mysql

Please correct me. Where am I going wrong.

Ajay
  • 570
  • 8
  • 17
  • Possible duplicate of [Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails](https://stackoverflow.com/questions/1253459/mysql-error-1452-cannot-add-or-update-a-child-row-a-foreign-key-constraint-fa) – raina77ow Dec 22 '17 at 06:22

1 Answers1

0

I have resolved it. Table member_history_logs must be empty only then you will be able to run Alter Table command.

Ajay
  • 570
  • 8
  • 17
  • One option is that `member_history_logs` table is empty. Another option is that all values in `element_id` column of the `member_history_logs` table exist in `members` table. See [db-fiddle](https://www.db-fiddle.com/f/5vGfGmd6kQBbMzSwzGSooQ/0) (error) and [db-fiddle](https://www.db-fiddle.com/f/iLv32XpvLdUY2F8AuuAmff/0). – wchiquito Dec 22 '17 at 10:12