MySQL查询语句相关语法汇总

  • Post author:
  • Post category:mysql


前言:查询语句是以后在工作中使用最多也是最复杂的用法,如何精准的查询出想要的结果以及用最合理的逻辑去查询尤为重要,使用好的语句逻辑可以大大降低查询的时间成本。

一、常用语句

1、select语句

MySQL中使用select来获取需要查询的数据结果,同时select也可以做输出,与print类似。

select * from <表名>;

2、where语句

where语句是用来作为条件判断的语句,多个条件之间用and或者or连接,返回结果是where语句中为True的结果。

select * from <表名> where <条件>;

3、having语句

having语句与where类似,都是用来作条件判断,区别在于,having语句查询的字段必须是在查询的结果中,having后面可以使用聚集函数,同时where所需要查询的字段必须在表中存在。


只能使用


where


不能使用


having


的情况。
select `name`, `birthday` from `student` where id > 2; 

-- 报错,having的条件查询,只能包含在前面的搜索结果里 
select `name`, `birthday` from `student` having id > 2;

只能使用


having


不能使用


where


的情况。
select name as n,birthday as b,id as i from student having i > 2; 

-- 报错,where只识别存在的字段 
select name as n,birthday as b,id as i from student where i > 2; 
-- 取出每个城市中满足最小出生年份大于1995的 
select city, group_concat(birthday) from student group by city having min(birthday) >'1995-1-1';

4、group by 分组查询

group by是按照某一字段对数据进行分组,如性别分为男女,可以查询出所有男生和女生的信息,如果有where字段要放在where字段之后。
select <字段> from <表名> where 条件  group by <分组字段>;

5、order by字段

order by是用来对查询的数据进行排序的语句,可以按照一定的规则进行排序,默认为升序(asc),降序需要在order by后面加上desc。

select * from <表名> order by <字段> desc;

6、limit语句

limit语句是用来对查询的结果做一些限制,限制只查询从某行到某行的结果。

select <字段> from <表名> limit m,n;
--其中m为从m行开始,n为向下查询n行

7、distinct语句

distinct语句是用来去重的语句,将查询的结果只显示一条。
select distinct <字段> from <表名>;

二、多表查询

1、union:联合查询

将两个或多个表联合查询,但需要保证查询两个表的结果字段数一致,查询的结果现实的字段是第一张表的字段。

select * from <表名> 
union
select * from <表名>;

2、inner join:内连接

inner join是将两张表按照某一字段进行匹配连接,显示在一起。

select <字段> from <表1> inner join <表2> on 表1.字段=表2.字段;

3、left join:左连接

left join是将左边表的查询字段全部显示,右边表没有匹配的行就显示为NULL。

select <字段> from <表1> left join <表2> on <表1.字段>=<表2.字段>;

4、right join:右连接

right join是将右边表的查询字段全部显示,左边表没有匹配的行就显示为NULL。

select <字段> from <表1> right join <表2> on <表1.字段>=<表2.字段>;



版权声明:本文为weixin_44747103原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。