12-4mysql 查询

简单查询
select * from 表名; 注意:*代表所有
);

查询指定列

select 列名,列名 from 表名


修改结果集的列名
select 列名 as'',列名 as'' from 表名

条件查询
select * from 表名 where 条件

多条件查询
select * from 表名 where 条件 or 条件
select * from 表名 where 条件 and 条件

范围查询
select * from 表名 where price>=40 and price<=60;
select * from 表名 where price betwen 60 and 80


离散查询
select * from 表名 where price in(20,30,40,50);
select * from 表名 where price not in(20,30,40,50)

模糊查询(关键字查询)
select * from 表名 where name like '%奥迪%' %代表任意多个字符

select * from 表名 where name like '_马%' _代表任意一个字符

9.排序查询
select * from car order by price asc asc升序(省略)
select * from car order by oil desc desc降序

先按照brand升序排,再按照price降序排
select * from car order by brand,price desc


去重查询
select distinct 列 from 表名

分页查询
一页显示10条,当前是第二页

select *from 表名 limit 10(跳过多少条),10(取第三条)

聚合函数(统计函数)

select count (主键) from 表名 查询数据总条数
select sum (列名) from 表名 求和
select avg(列名) from 表名 求平均
select max(列名) from 表名 求最大值
select min (列名) from 表名 求最小值

分组查询
查询汽车表中每个系列下有多少个汽车
select brand,count (*) from car group by brand
查询汽车表中所买的数量大于3的系列
select brand from car group by brand having count(*)>3


高级查询
1.连接查询,对结果集列的扩展
select *from 表1, 表2 #形成笛卡尔积
select *from 表1, 表2 where 表1.列=表2.列

select *from 表1join 表2 on 表1.列=表2.列

联合查询,对结果集行的扩张
select 列 from 表1
union
select 列 from 表2

子查询(里层查询)
父查询(外层查询)
子查询的结果作为父查询的条件
(1)无关子查询
子查询在执行时候和父查询没关系,子查询可以单独查询
1.查询民族为汉族的所有人员信息
父查询:select * from info where nation=()
子查询:select code from nation where name='汉族'
select * from info where nation=(select code from nation where name='汉族')
(2)相关子查询
子查询在执行时候和父查询有关系,子查询不可以单独查询

查询汽车表中油耗小于该系列平均油耗的汽车信息

父查询select *from car where oil<(该系列平均油耗)
子查询 select avg (oil) from car where brand=该系列

select *from car as a where oil<(select avg (oil) from car as b where b.brand=a.brand)

原文地址:https://www.cnblogs.com/F4natasy/p/6137774.html