天天看點

mysql insert update 一句_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語句更快,實際上是删除原來的表并建立一個表。