MySQL的基本语句

1.0数据库操作

# 创建数据库
create database test;

# 删除数据库
drop database test;

2.0 数据表操作

2.1 表的创建

# 创建数据表
create table account(
    id bigint primary key auto_increment comment '用户id',
    username varchar(20) unique comment '账号',
    `password` varchar(200) comment '密码',
    create_at timestamp default current_timestamp comment '创建时间',
    update_at timestamp on update current_timestamp comment '修改时间'
)comment '用户账号表';

2.2 表的修改

2.2.1 表中字段的添加

# 在 account 表中添加一个字段:role
alter table account add column role int comment '角色类型';

2.2.2 表中字段的修改

# 修改表 account 中 role 字段的类型
alter table account modify role varchar(10) comment '角色类型';

2.2.3 表中字段的删除

# 删除表 account 中的 role 字段
alter table account drop column role;

2.3 表的查询

2.3.1 查询数据库中所有的表

# 查询数据库 test 下的所有表
show tables from test;

2.3.2 查询表结构

# 方式一
show columns from account;
# 方式二
describe account;
# 方式三
desc account;

2.4 表的删除

drop table account;

2.5 表中数据的操作

2.5.1 表数据的查询

2.5.1.1 表中数据的简单查询
# 查询所有字段
select * from account;

# 查询所有字段
select id,username,password,create_at,update_at from account;

# 查询某个字段
select username from account;

# 查询某些字段
select id,username,password from account;
2.5.1.2 表中数据的条件查询
# 查询表 account 中 username 是 wbnyua 的用户
select id,username,password from account where username = 'wbnyua';

# 查询表 account 中 username 是 wbnyua 且 password 是 wbnyua123 的用户
select id,username,password from account where username = 'wbnyua' and password = 'wbnyua123';

# 查询表 account 中 username 不是 wbnyua 的用户
select id,username,password from account where username <> 'wbnyua';

# 查询表 account 中 username 前面6个字符是 wbnyua 的用户(包括用户名是 wbnyua)
select id,username,password from account where username like 'wbnyua%';

# 查询表 account 中 username 前面6个字符是 wbnyua ,后面个字符是其他任何字符的用户(不包括用户名是:wbnyua)
# (_ : 表示匹配任意字符)
select id,username,password from account where username like 'wbnyua_';

# 查询 id 在 1 到 3 之间的用户(不包括 id=1 和 id=3 )
select * from account where id > 1 and id < 3;

# 查询 id 在 1 到 3 之间的用户(包括 id=1 和 id=3 )
select * from account where id >= 1 and id <= 3;
# 这条查询语句等价与上面那条
select * from account where id between 1 and 3;

# 查询表 account 并根据 id 降序排序 (默认升序 asc)
select * from account order by id desc;

# 查询表 account 中 id=1 id=2 id=3 的用户
select * from account where id in (1,2,3);

# 查询语句还会更新

2.5.2 表数据的添加

# 添加一条数据
insert into account(username,password) value ('wbnyua','wbnyua123');

# 添加多条数据
insert into account(username,password) values ('wbnyua1','12345'),('wbnyua2','12345');

2.5.3 表数据的修改

# 修改语句的条件关键字的使用和查询语句差不多,就不展开写了

# 修改表 account 中 username 是 wbnyua 的 username 和 password
update account set username = 'wbnyua_admin' , password = '12345000' where username = 'wbnyua';

# 修改表 account 所有记录的 password 为 12345678
update account set password = '12345678';

2.5.3 表数据的删除

# 删除语句的条件关键字的使用和查询语句差不多,就不展开写了

# 删除表 account 中 username 是 wbnyua 的数据
delete from account where username = 'wbnyua';

# 清空数据(id 不会 从新开始递增)
delete from account;

# 截断表(id 会 从新开始递增)
truncate table account;
posted @ 2023-09-02 18:46  wbnyua  阅读(15)  评论(0编辑  收藏  举报