允许在现有外键列mysql中使用空值

时间:2014-11-11 13:09:04

标签: mysql

我有一个MySQL数据库,其中包含表格t1t2。表t1中的一列具有t2的外键。

需要允许外键列接受null值。已经存在一些重要数据,因此重新创建表格不是一种选择。

尝试了通常的alter table命令,但它显示了语法错误。 有没有办法绕过它而不影响数据库?

这就是我的尝试:

ALTER TABLE t1 MODIFY fk_column_id NULL;

1 个答案:

答案 0 :(得分:1)

缺少的部分是modify语句中的类型定义。使用MODIFY重新定义列,因此您还需要提供新类型。但是如果您只修改它可以为null,则不会丢失任何数据。

创建引用表并填充它:

mysql> -- Creating referenced table
mysql> create table `tUser` (
    -> `id` int auto_increment not null,
    -> `name` varchar(16),
    -> primary key (`id`)
    -> );
Query OK, 0 rows affected (0.07 sec)

mysql> -- Filling and checking referenced table
mysql> insert into `tUser` (`name`) values ("Jane"), ("John");
Query OK, 2 rows affected (0.04 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from `tUser`;
+----+------+
| id | name |
+----+------+
|  1 | Jane |
|  2 | John |
+----+------+
2 rows in set (0.07 sec)

mysql> -- Creating referencing table
mysql> create table `tHoliday` (
    -> `id` int auto_increment not null,
    -> `userId` int,
    -> `date` date,
    -> primary key (`id`),
    -> foreign key (`userId`) references `tUser` (`id`)
    -> );
Query OK, 0 rows affected (0.14 sec)

mysql> -- Filling and checking referencing table
mysql> insert into `tHoliday` (`userId`, `date`) values
    -> (1, "2014-11-10"),
    -> (1, "2014-11-13"),
    -> (2, "2014-10-10"),
    -> (2, "2014-12-10");
Query OK, 4 rows affected (0.08 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from `tHoliday`;
+----+--------+------------+
| id | userId | date       |
+----+--------+------------+
|  1 |      1 | 2014-11-10 |
|  2 |      1 | 2014-11-13 |
|  3 |      2 | 2014-10-10 |
|  4 |      2 | 2014-12-10 |
+----+--------+------------+
4 rows in set (0.05 sec)

mysql> -- Updating foreign key column to allow NULL
mysql> alter table `tHoliday` modify `userId` int null;
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> -- Inserting line without foreign key
mysql> insert into `tHoliday` (`date`) values ("2014-11-15");
Query OK, 1 row affected (0.06 sec)

mysql> select * from `tHoliday`;
+----+--------+------------+
| id | userId | date       |
+----+--------+------------+
|  1 |      1 | 2014-11-10 |
|  2 |      1 | 2014-11-13 |
|  3 |      2 | 2014-10-10 |
|  4 |      2 | 2014-12-10 |
|  5 |   NULL | 2014-11-15 |
+----+--------+------------+
5 rows in set (0.03 sec)