mysql对数据进行增删改查(crud)的操作

添加(create)

第一种方式

insert into 表名( 字段名称, 字段名称 ) values( 字段所对应的值, 字段所对应的值 ) 例:

第二种方式

insert into 表名 values( 字段所对应的值, 字段所对应的值, 字段所对应的值, 字段所对应的值 ) 注:这种方式一定要一一对应 例:

第三种方式

批量添加:

insert into 表名(字段,字段,字段) select 字段,字段,字段 from 表名;

例:

删除(delete)

第一种方式

delete from 表名 where 要删除的内容

一般使用主键来删除 例:

delete from book_tab where book_id = 10;

或:

delete from book_tab where book_id = 10;

全部删除:

delete from book_tab;

注:使用 delete 删除后,再添加时,主键会在原来的基础上自增长(即,之前用过 id 的不会被重复使用)

第二种方式

truncate table 表名; 这种删除方法会删除表中的所有内容,包括之前的自增长,再添加时,主键会从1重新开始

修改(update)

update 表名 set 字段=修改后的值 where 字段 = 值;

例:

update book_tab set book_title=三国演义 where book_id = 7;

修改多个时,可以使用逗号隔开 例:

update book_tab set book_title=红楼梦,book_price=33.33 where book_id = 6;

查询(retrieve)

(1)全查询

select 别名.* from 表名 as(可省略) 别名; 例:

select tk.* from three_kingdom_tab as tk;

select tk.* from three_kingdom_tab tk;

(2)查询其中的某一列或某几列 例:

select tk.tk_name,tk.tk_kingdom from three_kingdom_tab as tk;

同样可以在字段后加别名 例:

select tk.tk_name as 名字,tk.tk_kingdom as 国家 from three_kingdom_tab as tk;

(2)条件查询

关键字:> , < , >= , <= , <> , or , and , between…and select * from 表名 where 条件; 例:

select * from three_kingdom_tab where tk_age >= 50;

(2)多条件查询 例:

select * from three_kingdom_tab where tk_age >= 50 and tk_position = 将军;

其中:and 可以换为 or ,表示或者 在mysql中,不等于的符号为:<> 例:

select * from three_kingdom_tab where tk_age >= 50 and tk_position <> 君主;

还可以使用 between 来表示之间 例:

select * from three_kingdom_tab where tk_sal between 50000.00 and 70000.00;

(3)对 NULL 字段查询

关键字: is null , is not null 例:

select * from three_kingdom_tab where tk_manager is null;

查询不是 null 的:

select * from three_kingdom_tab where tk_manager is not null;

(4)模糊查询

关键字:like

例:找出所有姓张的人

select * from three_kingdom_tab where tk_name like 张%;

也可以使用下划线表示后面字的个数(一个下划线代表黄后边有一个字,两个同理) 例:

select * from three_kingdom_tab where tk_name like 张_;

(5)对查询的结果排序

关键字:order by (asc, desc)

其中:asc代表正序,desc代表逆序。不写默认为asc正序

与其他条件同时使用时,order by需写在后面

例:

select * from three_kingdom_tab order by tk_age;

(6)限制查询的行数

关键字:limit

例: 找出年龄最大的五个人

select * from three_kingdom_tab order by tk_age desc limit 0,5;
经验分享 程序员 微信小程序 职场和发展