SELECT ... INSERT with NOT NULL字段

时间:2013-12-19 02:34:42

标签: mysql sql

我正在尝试将SELECT... INSERT放入具有阻止NULL值的约束的表中:

mysql> create table if not exists table1 (
    -> id int not null auto_increment,
    -> description varchar(45),
    -> primary key (`id`)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> create table if not exists table2 (
    -> id int not null auto_increment,
    -> description varchar(45) not null,
    -> primary key (`id`),
    -> unique index `unique_desc` (`description`)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> insert ignore into table1
    -> (description)
    -> values("stupid thing"),
    -> ("another thing"),
    -> (null),
    -> ("stupid thing"),
    -> ("last thing");
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from table1;
+----+---------------+
| id | description   |
+----+---------------+
|  1 | stupid thing  |
|  2 | another thing |
|  3 | NULL          |
|  4 | stupid thing  |
|  5 | last thing    |
+----+---------------+
5 rows in set (0.00 sec)

很酷,我们创建了源(table1)和目标(table2)表,并且源表填充了一些重复的空数据。

如果我在目标表中执行正常SELECT... INSERT,我会得到一个空字符串作为值的列:

mysql> insert ignore into table2
    -> (description)
    -> select description
    -> from table1;
Query OK, 4 rows affected, 1 warning (0.00 sec)
Records: 5  Duplicates: 1  Warnings: 1

mysql> select * from table2;
+----+---------------+
| id | description   |
+----+---------------+
|  3 |               |
|  2 | another thing |
|  4 | last thing    |
|  1 | stupid thing  |
+----+---------------+
4 rows in set (0.00 sec)

这很糟糕。但是一些老板布莱克默在这个问题上引导我回答:

MySQL Insert Select - NOT NULL fields

现在这种方法给了我想要的结果:

mysql> insert ignore into table2
    -> (description)
    -> select description
    -> from table1
    -> where description <> '' and description is not null;
Query OK, 3 rows affected (0.00 sec)
Records: 4  Duplicates: 1  Warnings: 0

mysql> select * from table2;
+----+---------------+
| id | description   |
+----+---------------+
|  2 | another thing |
|  3 | last thing    |
|  1 | stupid thing  |
+----+---------------+
3 rows in set (0.00 sec)

我是否有办法获得上述结果而无需使用WHERE子句手动保护每个字段?

提前致谢,

ķ

1 个答案:

答案 0 :(得分:1)

这从技术上回答了您的问题,因为您可以通过 join 而不是 where 子句来消除空值。

insert ignore into table2
(description)
select t.description from table1 t
join 
(
select distinct description from table1
) t1 on (t.description=t1.description);

但是,我很确定您需要为每个字段指定连接。在我的头脑中,我无法想到解决这个问题的方法。