数据库的语法
- 查看数据库:
show databases;
- 显示当前数据库的时间:
select now();
- 显示数据库的版本:
select version();
- 创建数据库:
sqlcreate database 数据表的名称;
- 指定数据库的编码:
create database 数据表的名称 charset=编码名称;
- 查看数据库编码:
show create database 数据表的名称;
- 删除数据库:
drop database 数据表的名称;
- 查看当前使用的数据库:
select database();
- 使用数据库:
use 数据库名称;
- 显示当前数据库中所有的表:
show tables;
- 查看数据表的结构:
desc 数据表的名称;
- 数据表的约束:
- 创建数据表:
create table gwl(id int, name varchar(30));
-
数据表的约束:`create table gwl2(id int, primary key not null auto_increment, name varchar)`
create table gwl3(
id int unsigned not null auto_increment primary key,
name varchar(30),
age tinyint unsigned default 0,
high decimal(5,2),
gender enum("男", " 女", "保密") default "保密",
cls_id int unsigned
);
数据表的插入
16. 数据的插入:`insert into gwl values(0, "gwl", 18, 170.88, "男", 0);`
17.查看插入的数据:`select * from gwl;`
18.部分插入: insert into (name, gender) values(''gwl", "男");
19.多行插入:insert into gwl (name, gender) values ("gwl", "男"), ("gwl2", "男");
数据表的增删改查
- 修改表-添加字段:
alter table 表名 add 列名 类型;
alter table gwl add birthday datetime;
2.修改表-修改字段--不重名:
alter table 表名 modify 列名 类型以及约束;
alter table gwl modify birthday datetime;
3.修改字段--重命名:
alter table 表名 change 原名 新名 类型以及约束;
alter table gwl change birthday birth date defalut "2003-01-01";
3.删除字段
alter table 表名 drop 列名;
alter table gwl drop high;
3.删除表
drop table 表名;
--删除数据库
drop database 数据库;
--删除数据表
drop table 数据表;
修改数据
- 修改数据库的数据:
update gwl set age=2, gender="男" where id=2;
物理删除
- 清空数据表:
delete from gwl;
- 物理删除:delete from 表名 where 条件:
delete from gwl where name="gwl";
- 逻辑删除:
alter table gwl add is_delete bit defalut 0;
update gwl set is_delete=1 where id=6;
查询
-
去重关键字: distinct 字段:select distinct gender from gwl;
-
查询:
--模糊查询:
-- like
-- %代替1个或多个
-- _替换一个
select * from gwl where name like "小%";
--查询包含小的所有名字
select * from gwl where name like "%小%";
--查询两个字的名字
select * from gwl where name like "__";
--查询三个字的名字
select * from gwl where name like "___";
-- rlike 正则表达式
-- 查询以古为开头的
select * from gwl where name rlike "^周.*";
--以周开头以伦结尾的
select * from gwl where name rilke "^周.*伦$";
排序:
数据排序
-- 排序:
--asc 从小到大排序
--desc 从大到小排序
--查询年龄在18到28之间的男性, 按照年龄从大到小排序
select * from gwl where (age between 18 and 28) and gender=1 order by asc;
select * from gwl where (age between 18 and 28) and gender=1 order by desc;