MySQL常用语句

MySQL经典语句

学编程的绕不开的一环,就是数据库,常用的就是MySQL了。本文整理了部分SQL语句的书写格式,以便后续查看。

1、创建数据库

create database 数据库名;

create database webapp;

2、创建数据表

create table 数据库名.表名(
	字段名1 字段类型(字段长度) 约束 comment '备注内容',
	字段名2 字段类型(字段长度) 约束 comment '备注内容'
);

create table webapp.t_user(
    id int(11) not null primary key auto_increment comment '用户表',
    username varchar(20) not null comment '用户名',
    password varchar(18) not null comment '用户密码',
    role_id int(11) comment '用户角色',
    gmt_create datetime default current_timestamp comment '创建时间',
    gmt_modified datetime default current_timestamp on update current_timestamp comment '更新时间'
);

# 约束:
根据约束数据列限制,约束可分为:
	单列约束:每个约束只约束一列;
	多列约束:每个约束约束多列数据。
	
下面是常用的约束类型:
primary key:主键约束:表示当前字段为表的主键,主键数据不能重复;
auto_increment:自增长,用于主键上面的话,每插入一条数据会自动加一;
not null:非空约束,表示当前字段不能为空;
default:默认值,“创建时间”和“修改时间”两个地方我使用了默认值,当插入数据和修改数据时,会自动进行更新时间数据;
unique: 唯一约束,指定某列和几列组合的数据不能重复;
foreign key:外键,指定该列记录属于主表中的一条记录,参照另一条数据;
check:检查,指定一个表达式,用于检验指定数据;
(注意: MySQL不支持check约束,但可以使用check约束,而没有任何效果)

3、修改数据库、数据表的字符集

alter database 数据库名 character set 字符集;
alter table 数据表名 convert to character set 字符集;

alter database webapp character set utf8mb4;
alter table webapp.t_role convert to character set utf8mb4;

4、插入数据

insert into 数据表名 (字段一,字段二) values (数据a1,数据a2),(数据b1,数据b2);

insert into webapp.t_role (role_name, role_explain)
values ('角色二','无用的'),('角色三','无苛刻的');

5、修改数据

update 数据表名 set 字段名 = 修改值,字段名 = 修改值 where 判断条件;

update webapp.t_role set role_name = '角色一百',role_explain = '修改成功' where id = 3;

6、查询数据

select 表字段名 from 表名 where 条件;
# where 可以省略,代表查询全表数据
# 表字段可以用 * 代替,表示查询表所有字段

select * from t_role;
select role_name from t_role where id = 2;

7、删除数据

不写where,会将表中全部数据进行删除

delete from 数据表名 where 条件;

delete from t_role where ``.t_role.id = 2;

8、查询数据分割与替换

分割、替换不影响表中的数据,只是查询出来的数据改变了

select substring_index(字段名, 分割符, 取第几个分隔符之间的内容)
from 表名;

select substring_index(tp.permissions, '|', -3)
from t_permissions tp;
select replace(字段名, 被替换字符串, 替换字符串) [别名] from 表名;

select replace(tp.permissions, '|', ',') replas from t_permissions tp;

文章参考:
SQL基础语句
字符串分割与替换


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值