show databases;查看所有数据库
create database 库名;创建数据库
create table 表名 (
列名 数据类型(长度) primary key,
列名 数据类型(长度) ,
列名 数据类型(长度) ,
列名 数据类型(长度),
列名 数据类型(长度)
);
drop database 库名;删除数据库
use 库名;使用数据库
create table 表名;创建表
drop table 表名;删除表
show tables;查看所有表
desc 表名;查看表结构
表的内容:
添加内容: insert into 表名 valus(值1,值2),(值1,值2),(值1,值2);
查询内容:select 列名 from 表名 //*代表全部,可查看整个表;
修改内容: update 表名 set 列名1=值1,列名2=值2;
删除内容:delete from 表名;
查询语句:
简单查询:select 列名 from 表名
条件查询:select 列名 from 表名 where 列名 = 条件,多条件用 and或者or连接多个条件
模糊查询:select 列名 from 表名 where 列名 like ' 字符_'; _代表字符前后有多少个字,%代表随意多个字,%字符%
排序查询:select 列名 from 表名 order by 列名 desc/asc;asc为升序,是默认的,desc为降序
范围查询:select 列名 from 表名 where 列名 >=60 and 列名 <=80 / 列名 between 60 and 80
离散查询:但需要查询多个同列名条件时使用
select 列名 from 表名 where 列名 in('xx','xx','xx') / not in ('xx','xx','xx')
聚合函数,统计查询:select sum(列名) from 表名 / sum求和,count数据条数,max最大,min最小,avg平均
分页查询:select 列名 from 表名 limit (n-1)*5,5
去重查询:在 select后面加distinct
select distinct 列名 from 表名;
分组查询:
select count(*),列名 from 表名 group by 列名
select 列名 from 表名 group by 列名 having count(*)>3 #分组之后根据条件查询使用having 不使用where
高级查询
连接查询:select 列名 from 表名,表名,表名 //会形成笛卡儿积,出现大量重复
添加条件去除笛卡儿积 where 表名.列名 = 表名.列名 //两个列名必须相同且两个表中必须同时存在
联合查询:多个select用union连接
select 列名 from 表名 union select 列名 from 表名
无关子查询:子查询的结果当做父查询的条件
select 列名 from 表名 where 条件名 = (select 列名 from 表名 where 。。。)
相关子查询:
查询汽车表中油耗低于该系列平均油耗的所有汽车信息
父查询:select * from Car where Oil<(该系列平均油耗)
子查询:select avg(Oil) from Car where Brand = '某个系列'
select * from Car a where Oil<(select avg(Oil) from Car b where b.Brand = a.Brand )