登录数据库:
说明:
-u 后面是登录的用户名
-p 后面是登录密码,如果不填写,回车之后,会提示输入密码
登录成功后,输入如下命令查看效果:
select now();
推出数据库:
quit 或 exit 或 ctrl+d
数据库操作的SQL
查看所有数据库:
show databases;
创建数据库:
create database 数据库名 charset=utf8;
使用数据库:
use 数据库名;
查看当前使用的数据库:
select database();
删除数据库 --慎用:
drop database 数据库名;
表结构操作的SQL语句
1.查看当前数据库所有表
show tables;
2.创建表
create table 表名称 (字段名称 数据类型 可选的约束条件,
colunl datatype comtrai);
3.查看表结构
desc 表名称;
4.修改表-添加段
alter table 表名称 add 列名称 类型 约束;
具体操作:
注: modify:只能修改数据类型或者约束条件,不能修改列名称
5.修改表-修改字段名称和字段类型
alter table 表名称 change 原名称 新名称 类型及约束;
具体操作:
6. 修改表-删除字段
alter table 表名称 drop 列名称;
7.查看创建表
--查看表结构的属性信息
show create table 表名称;
8.创建数据库
--查看数据库的属性信息
show create database 库名称;
9.删除表
drop table 表名称
数据库基本操作2:
1.查询数据
select * from 表名称
2.添加数据
--全列插入,值顺序必与列字段顺序一致
insert into 表名称 values(值1,值2,值3...);
--部分列插入,值的顺序与给出的列顺序对应
insert into 表名称(列1,列2...) values(值1,值2...);
--全列多行插入
insert into 表名称 value (值1,值2...),(值1,值2...),(值1,值2...);
--部分列多行插入
insert into 表名称(列1,列2...) values (值1,值2...),(值1,值2...);
说明:
-
主键列是自动增长,但是在全列插入时需要占位,通常使用空值(0或者null或者default)
-
在全列插入时,如果字段列有默认值可以使用default来占位,插入后的数据就是之前设置的默认值
3.修改数据
update 表名称 set 列1= 值1,... where 条件;
4.删除数据
delete from 表名称 where 条件;
问题:
逻辑删除,添加删除标识isdelete字段,0代表未删除,1代表删除
as和distinct使用
--as就是别名
select 列名称 as 别名 from 表名称;
--也可以用空格代替as
select 列名称 空格 别名 from 表名称;
--distinct去重
select distinct 列名称 from 表名称;
order by和asc、desc排序
1.asc:升序
2.desc:降序
--asc升序排序
select * from 表名称 order by 列名称 asc;
--desc降序排序
select * from 表名称 order by 列名称 desc
where条件搭配运算符<、>、<=、>=、!=、=使用
--运算符:<
select * from 表名称 where 列名称 < 值;
--运算符:>
select * from 表名称 where 列名称 > 值;
--运算符:<=
select * from 表名称 where 列名称 <= 值;
--运算符:>=
select * from 表名称 where 列名称 >= 值;
--运算符:!=
select * from 表名称 where 列名称 != 值;
--运算符:=
select * from 表名称 where 列名称 = 值;
where条件搭配like模糊查询使用
--like是模糊查询的关键字
1.%表示多个任意字符
--查询姓黄的人
select * from 表名称 where 列名称 like '黄%';
2._表示一个任意字符
--查询姓黄且名字里只有一个字的人
select * from 表名称 where 列名称 like '黄_';
where条件搭配not、and、or使用
--and:条件需要全部满足
select * from 表名称 where 列名称1 = 值 and 列名称2 = 值;
--or:条件中满足一个即可
select * from 表名称 where 列名称1 = 值 or 列名称2 = 值;
--not判断...不在...之间
select * from 表名称 where not(列名称=值1,列名称>值2...);
where条件范围查询
bewtten...and...表示在一个连续的范围内查询
in表示在一个非连续的范围内查询
--between and 连续范围查询
select * from 表名称 where 列名称 between 值1 and 值2;
--in非连续范围查询
select * from 表名称 where in(值1,值2,值3...);
-
where条件 --- 空判断
-
判断为空使用: is null
-
判断非空使用:is not null
--is null判断值为空 select * from 表名称 where 列名称 is null; --is not null判断值不为空 select * from 表名称 where 列名称 is not null;