mysql insert update delete

insert

insert [into] t [(col_name,...)] values(v1,v2...)

如果省略了列名,那么values里必须有所有列的值,自增列的值为null

如果指定了部分列名,其他的列必须允许为null或指定了默认值

连续插入

insert into table(name, address, zip)

values('zhangsan', '江苏', '222100'),

('lisi', '上海', '220300');

插入select的结果

insert into customers(id,name,email) select uid,uname,uemail from custnew;

列名不需要相同,重要的是列的位置,将select的第k列插入到insert的第k列

降低插入语句的优先级,对update和delete同样适用

insert low priority into..

唯一索引,记录重复时可选择只更新指定字段,或者保留老记录,或者用新纪录整条替换老记录

只更新指定字段:on duplicate key update

insert into table(a,b)

select c,d from t

on duplicate key update b=values(a)+values(b) //values(b)是想插入的新记录里b的值

保留老记录:insert ignore into

替换老记录:replace into

update

update t set name='zhangsan', email = '[email protected]' where id=1;

update a inner join b on a.id=b.uid set type = utype; 多表更新

update ignore t... 某行发生错误,其它行继续更新

update a, b set a.title=b.title, a.name=b.name where a.id=b.id 用另一个表的数据更新

delete

delete from t where id=1;

delete t1 from t1 left join (select ..) as t2 on t1.id=t2.id where t2.name='abc'; 多表删除

如果想删除所有行,用truncate table语句更快,实际上是删除原来的表并新建一个表。

猜你喜欢

转载自www.cnblogs.com/ts65214/p/12976055.html