Yes, it is possible, although you only need to bypass the foreign key constraint once to insert a dummy entry for the default value. Here is my workflow:
This creates a table:
root@localhost:playground > create table comments(id int auto_increment primary key, parent_id int not null default 0, constraint fk_parent_id foreign key (parent_id) references comments(id) on delete cascade on update cascade)engine=innodb; Query OK, 0 rows affected (0.01 sec) root@localhost:playground > show create table comments\G *************************** 1. row *************************** Table: comments Create Table: CREATE TABLE `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `fk_parent_id` (`parent_id`), CONSTRAINT `fk_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `comments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1 1 row in set (0.00 sec)
Now bypass the foreign key and insert the dummy entry.
root@localhost:playground > set session foreign_key_checks=0; Query OK, 0 rows affected (0.00 sec) root@localhost:playground > insert into comments (id) values (null); Query OK, 1 row affected (0.00 sec) root@localhost:playground > set session foreign_key_checks=1; Query OK, 0 rows affected (0.00 sec) root@localhost:playground > select * from comments; +----+-----------+ | id | parent_id | +----+-----------+ | 1 | 0 | +----+-----------+ 1 row in set (0.00 sec) root@localhost:playground > update comments set id = 0 where id = 1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 root@localhost:playground > select * from comments; +----+-----------+ | id | parent_id | +----+-----------+ | 0 | 0 | +----+-----------+ 1 row in set (0.00 sec)
To make things neat and tidy, I reset auto_increment (this is optional):
root@localhost:playground > alter table comments auto_increment=0; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0
And now your foreign key constraint is working correctly, and your column is no longer valid and has a default value:
root@localhost:playground > insert into comments (id) values (null); Query OK, 1 row affected (0.00 sec) root@localhost:playground > select * from comments; +----+-----------+ | id | parent_id | +----+-----------+ | 0 | 0 | | 1 | 0 | +----+-----------+ 2 rows in set (0.00 sec)
fancyPants
source share