数据库语句介绍:
语言分类:
DDL:数据库和表
DML:表中的数据
DQL:查询表中的数据
DCL:(授权)
DDL:
1、操作数据库
创建数据库:
create database 数据库名;
创建数据库,判断是否存在,如果不存在再创建:
create database if not exists 数据库名;
创建数据库,并指定字符集:
create database 数据库名 character set 字符集名
查看所有数据库:
show databases;
查看数据库创建语句:
show create database 数据库名;
切换数据库:
use 数据库名;
修改数据库字符集:
alter database 数据库名 character set utf8;
删除数据库:
drop database 数据库名;
drop database if exists 数据库名;
2、操作表
创建表:
create table 表名(
列名1 类型1,
列名2 类型2,
列名3 类型3);
mysql数据类型:
1、int:整数类型
2、double:小数类型
3、date:日期(yyyy-MM-dd)
4、datetime:日期(yyyy-MM-dd HH:mm:ss)
5、datestamp:时间戳类型(yyyy-MM-dd HH:mm:ss)
注意:如果不给时间戳赋值或者赋值为null 那么它会默认获取当前时间
6、varchar:字符串
复制表:
create table 表名 like 被复制的表名;
查看表结构:
desc student;
查看所有表:
show tables;
修改表名:
alter table student rename to stu;
修该表的字符集:
alter table student character set 字符集;
添加一列:
alter table 表名 add 列名 数据类型;
修改列名:
alter table stu change 原列名 新列名 新数据类型;
alter table stu modify 列名 新数据类型;
删除列:
alter table stu drop 列名;
删除表:
drop table 表名;
drop table if exists 表名;
DML:表中的数据
1、添加数据:
insert into 表名(列名1,列名2,列名3……)values(值1,值2,值3……);
注意:列名和值要一一对应
insert into 表名 values(值1,值2,值3……);
注意:如果不写列名 ,那么默认就是添加所有
除了数字类型,其他类型需要用引号(单双都是可以的)引起来;
一次性添加多行数据:
insert into stu values(2,'dodo',15),(3,'hoho',45),(5,'roro',25);
查询所有:select * from stu;
2、删除数据
delete from 表名 where 条件
注意:如果不加条件,删除表中所有的数据
3、删除全部数据:
1、delete from 表名; (效率低,不推荐使用)一条一条的删除(数据)
2、truncate table 表名; (效率高 推荐使用) 直接把表删除 然后再重写创建一张表
4、修改:
update 表名 set 列名1 = 值1,列2 = 值2 where 条件;
注意:如果不加条件 就会修改表中所有的数据
DQL:查询数据
基础查询:
查询所有:
select * from 表名;
根据条件查询:
select * from 表名 where 条件
查询某一列数据:
select 列名 from 表名 where 条件
ifnull(表达式1,表达式2);
表达式1:哪个字段需要判断是否为空
表达式2:如果为空,就替换成该值
select id,stu_name,ifnull(age,0) from stu where id = 2;
as:起别名 as可省略
select id,stu_name,ifnull(age,0) age from stu where id = 2;
条件查询:
1、where子句后跟条件
2、运算符
<,>,<=,>=,<>(不等于)
select * from stu where id <> 2;
between and :在两者之间 (包含两头)
select * from stu where id between 2 and 5;
in:集合
select * from stu where id in(2,3,5);
like:模糊查询
占位符
_:一个字符
select * from stu where stu_name like 'ho_o';
%:多个字符
select * from stu where stu_name like '%o';
is null:
select * from stu where age is null;
and / &&:
or /||:
not / !: