总之就是次序很重要,但是次序很容易输入出错,所以这样写不安全
也更繁琐,有个明确的对应关系,出错的概率就小很多
insert into Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email) values('1000000006', 'Toy Land', '123 Any Street', 'New York', 'NY', '11111', 'USA', null, null);由于我前面已经插入了这一行,所以这次插入同样的数据,出错了,但是代码本身没错哦
这种写法,可以换values列表的输入次序,只要把前面表名后括号中的项的顺序也改一改就好了,保证对应关系正确
insert into Customers(cust_id, cust_contact, cust_email, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country) values('1000000006', null, null, 'Toy Land', '123 Any Street', 'New York', 'NY', '11111', 'USA');当然还是报duplicate entry错误啦
即只给某些列提供值,其他列不给值就行了。但是必须保证不给值的那些列允许是null值或者有默认值才可以
insert into Customers(cust_id, cust_contact, cust_email, cust_name, cust_address, cust_city, cust_state) values('1000000006', null, null, 'Toy Land', '123 Any Street', 'New York', 'NY');当然还是报duplicate entry错误啦
示例代码
insert into Customers(cust_id, cust_contact, cust_email, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country) select cust_id, cust_contact, cust_email, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country from CustNew;这个代码会报错,因为我们的数据库没有CustNew这个表。但是不影响学习这个知识
insert select可以用一个select语句插入多行不要求insert into后表名括号中的列名和后面select后的列名一样,因为DBMS操作的是列的位置,列名只是给出位置而已,他可以正确解析。insert select中的select语句可以包含where子句。mysql不支持这种语法。。。 它要这么写:
CREATE table CustCopy as select * from Customers;但我觉得还是select into更好,很易懂
关键字
intovaluesselect into:把行导入到一个新表insert select:从其他表导入行create table