您的位置:首页 > 数据库 > MySQL

MySQL查询语句集合

2017-12-12 17:33 393 查看
简单查询:

一:查询所有数据

select * from Info 查所有数据

select Code,Name from Info 查特定列

二:根据条件查

select * from Info where Code='p001' 一个条件查询

select * from Info where Code='p001' and Nation='n001' 多条件 并关系 查询

select * from Info where Name='胡军' or Nation='n001' 多条件 或关系 查询

select * from Car where Price>=50 and Price<=60 范围查询

select * from Car where Price between 50 and 60 范围查询

三:模糊查询

select * from Car where Name like '%型' %通配符代表任意多个字符

select * from Car where Name like '%奥迪%' _通配符代表任意一个字符

select * from Car where Name like '_马%'

四:排序

select * from Car order by Price asc 按照价格升序排列

select * from Car order by Price desc 按照价格降序排列

select * from Car order by Price,Oil 按照两列进行排序,前面的为主要的

五:统计函数(聚合函数)

select count(Code) from Car 查询表中有多少条数据

select max(Price) from Car 取价格的最大值

select min(Price) from Car 取价格的最小值

select sum(Price) from Car 取价格的总和

select avg(Price) from Car 取价格的平均值

六:分组查询

select Brand from Car group by Brand having count(*)>2 查询所有系列中数量大于2的

七:分页查询

select * from Car limit 0,5 跳过几条数据取几条数据

八:去重查询

select distinct Brand from Car


高级查询:

一:多表连接

1.select Info.Code,Info.Name,Nation.Name from Info,Nation where Info.Nation = Nation.Code 查几张表就就输出几张表,查那个条件就输出那个条件 列的查询

select * from Info,Nation 全部输出4x4

2.连接查询

1、内连接:将两个表中存在连结关系的字段符合连接条件的记录形成记录集

Select A.name,B.name from A inner join B on A.id=B.id和

Select A.name,B.name from A,B where A.id=B.id结果是一样的(内连接的inner关键字可省略);

2、外连接:分为左外连接和右外连接

左连接A、B表结果包括A的全部记录和符合条件的B的记录。

右联结A、B表的结果和左联结B、A的结果是一样的,也就是说:

Select A.name,B.name from A Left Join B on A.id=B.id和

Select A.name,B.name from B Right Join A on B.id-A.id执行后的结果是一样的。



二:多表联合

select * from Info where Code='p001'union select * from Info where Nation='n001' union 联合 行的查询

三:子查询(无关子查询) 

select * from Info where Nation = (select Code from Nation where Name='汉族') 两个查询 一个查询的结果当做另一个查询的条件 查一个 =

select * from Info where Nation in (select Code from Nation where Name='汉族' or Name='苗族') 

in(在里面)not in (在不里面)任意一个都可以 作为两个查询结果的链接 查两个in

四:子查询(相关子查询)

select * from Car a where a.Oil <(select avg(Oil) from Car b where b.Brand = a.Brand) 

把外子查询定义一个a 里面的表定义成b 外层表看油耗 里层求油耗的平均值(每一个数据都走一遍)


五:合并查询
1.union
使用union关键字是,数据库系统会将所有的查询结果合并到一起,然后去掉相同的记录;
select id from t_book union select id from t_bookType;
2.union all
使用union all,不会去除掉重复的记录;
select id from t_book union all select id from t_bookType;

转自:http://www.cnblogs.com/cuikang/p/6054046.html

转自:http://www.cnblogs.com/cuikang/p/6054058.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  MySQL