create table tb(
id int primary key auto_increment,
name varchar(5),
age int );
1.各种数据增加方法
上面表中,name和age都可以为空,则在插入语句时可以有如下选择:
insert into tb values ( null,”name”, 3); //id值为null,主键会自动增加,全值插入,不需要写前面内容。
insert into tb (id) values ( 2);
insert into tb (id, name) values (3, “hi”);
insert into tb (id, name) values (4, “hi”), values(3, “more”); //一次性插入多条数据。
insert into tb set id=5; //set 的语法不常用
insert into tb set id=6, name=“hello”;
2.当主键冲突时,可选执行更新。
注意这个冲突primary key,unique key的更新操作,update后面没有set
insert into tb values(6, name=“high”,3) on duplicate keyupdate name=“high”, age=3;
3.子查询结果插入
用下面这个语句,可以将另外一张表中得部分数据取出放入一个新表。
insert into tb(name, age) select name, age from tb; //从自己表中复制 蠕虫复制
insert into tb1(name, age) select name, age from tb2 //从别的表中复制
4.default
insert into tb values(default, “high”, default); //主键的default是自动+1, age的default是NULL
insert into tb values(default, “high”, default(age));
5.replace
replace into tb(5, “replace name”, 3); //如果存在主键id 5,则替换,否则插入
replace into tb(null, “replace name”, 3); //自动增加
replace into tb(default, “replace name”, 3); //自动增加
6.删除数据
delete from tb order by id limit 10;删除最小的10个id的数据。
用连接的语法同时删除连接的两个表的数据。可以替代外键的on delete cascade功能。
delete from one, two using one join two on one.id=two.id where one.id=2;
delete from one, two using one join twowhere one.id=two.id and one.id=2;
7.删除数据 truncate
truncate table_name; //将整个表直接删除,然后再新建一个表。这样主键id信息不会被保留。
而delete from tb_name;//主键id,会保留,再添加时,会延续被删除数据的值。
8.更新数据
mysql> update one set name="ok" where id<4; //更新所有id小于4的值
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> update one set name="2" where id<4limit 2; //只更新前两个
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
update one set name="2" where id<4order by name limit 2;
9.连接更新
update one join two on one.id=two.id set one.name="new", two.name="two";
delete from one, two using one join two where one.id=two.id and one.id=2;
<完>