我試圖做一個SELECT... INSERT
入表,以防止NULL值的約束:創建SELECT ... INSERT與NOT 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)
酷,大家都有源(表1)和目標(表2)表,並且源表填充了一些重複的空數據。
如果我做一個正常的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)
這是不好的。但一些老闆brogrammer促使我在這個問題的答案:
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
條款手動保護每個字段?
由於提前,
ķ
您可以在新表上嘗試一個'BEFORE INSERT'觸發器並拒絕空值 - 'INSERT IGNORE'應該跳過該行。 –
再次感謝您的回覆,兄弟。我認爲,如果我必須在寫入觸發器和手動保護每個NOT NULL列之間選擇,我寧願手動保護,正如您在示例中指出的那樣。我只需要相信在這裏有一個解決方法,無論是使用設置還是使用不同的方法來批量插入。有人曾經有過這個問題。 – kbuilds