数据库操作
一、查看所有的数据库
show databases;
二、创建数据库
create database userinfo;
说明:
创建了一个名为userinfo的数据库
三、使用数据库
use userinfo;
四、显示数据库中的所有表
show tables
数据表操作
一、创建表
create table tab1(nid int, name char(10));
说明:
创建了列名为nid,类型为int类型及列名为name,类型为char,字符长度为10的,名为tb1的表。
实例:
create table tb2(
nid int not null auto_increment,
name varchar(255),
pwd varchar(255),
primary key(nid)
) engine=innodb default charset=utf8;
二、删除表
drop table 表名
三、清空表
1、delete from tb1
这个清空 ,只会将表中的内容清空,设置的 比如,自增效果;是不会清除的,如果清空后再增加数据,数据会接着上次清空的序号开始增加。
2、truncate table tb1
清空内容,也会将效果清除,比如,自增。
四、修改表
添加列:alter table 表名 add 列名 类型
删除列:alter table 表名 drop column 列名
修改列:
alter table 表名 modify column 列名 类型; -- 类型
alter table 表名 change 原列名 新列名 类型; -- 列名,类型 添加主键:
alter table 表名 add primary key(列名);
删除主键:
alter table 表名 drop primary key;
alter table 表名 modify 列名 int, drop primary key; 添加外键:alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
删除外键:alter table 表名 drop foreign key 外键名称 修改默认值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
删除默认值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
表内容操作
一、对表插入内容
insert into tb1 (nid,name,pws) values(2,'haha','123');
- 插入多个内容:
insert into tb1 (nid,name,pws) values(3,'haha','123'),(4,'xxx','113'),(5,'sss','666');
说明:
前面在创建表的时候,nid为主键,而且自增,所以增加内容的时候,nid不能重复,不然增加不进去。
二、删除表的内容
delete from 表
delete from 表 where id=1 and name='xxx'
三、修改表的内容
update 表 set name = 'xxx' where id>1
四、查看表的内容
select * from tb1;
- 加入判断条件的查看
select * from 表
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1
注意:
操作SQL方法的时候,默认是以分号“ ; ”,表示一段语句的结束;因此我们执行语句的时候,一条完整的语句结束时必须加结束符号分号,不然运行会不成功。
五、其他
1、条件
select * from 表 where id > 1 and name != 'xxx' and num = 12; select * from 表 where id between 5 and 16; select * from 表 where id in (11,22,33)
select * from 表 where id not in (11,22,33)
select * from 表 where id in (select nid from 表)
2、通配符和模糊匹配
select * from 表 where name like 'ale%' - ale开头的所有(多个字符串) select * from 表 where name like 'ale_' - ale开头的所有(一个字符)
3、限制
select * from 表 limit 5; - 前5行
select * from 表 limit 4,5; - 从第4行开始的5行
select * from 表 limit 5 offset 4 - 从第4行开始的5行
4、排序
select * from 表 order by 列 asc - 根据 “列” 从小到大排列
select * from 表 order by 列 desc - 根据 “列” 从大到小排列
select * from 表 order by 列1 desc,列2 asc - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
说明:
- 从大到小 desc
- 从小到大 asc
5、分组
select num from 表 group by num
select num,nid from 表 group by num,nid
select num,nid from 表 where nid > 10 group by num,nid order by nid desc
select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid select num from 表 group by num having max(id) > 10 –获取id大于10中最大的id
特别的:
group
by
必须在
where
之后,
order
by
之前
6、组合
组合,自动处理重合
select nickname
from A
union
select name
from B
组合,不处理重合
select nickname
from A
union all
select name
from B