mysql知识点汇总

来源:互联网 发布:大数据的特点包含 编辑:程序博客网 时间:2024/06/05 10:24

个人喜欢小写,所以在使用命令行的时候都是用的小写。


第一部分:简单非通配查询:

select distinct username from user;从user表中查出有多少不同的username


select username from user limit 5,5;从第六行开始查询,一共查询5行


select user.username from user;使用完全限定的表名


select username from user order by useaname;已username进行排序


select username,password from user order by username,password;只有在多个username的值相同时,才会按password进行排序,如果username中所有的值都是唯一的,则不会按password进行排序


 select username,password from user order by username desc;按username进行降序排列


select username,password from user order by username desc,password;按username降序排列,然后再对password进行排序


select username from user order by username desc limit 1;找出最大的username


不等于符号:<>  !=  


select username from user where username = 11 or username != 22;or进行条件的选择


select id from id_user where id  not in (1,10);不在这个范围内


第二部分:用通配符进行过滤


select username from user where username like "x%";查询所有以x字母开头的username


select username from user where username like "%x%";查询所有只要username中含有x字母的username


select username from user where username like "x%g";查询所有以x开头,以g结尾的username


select username from user where username like "%";等价于 select username from user;

//注意,%不能匹配null值


select username from user where username like "_a";_跟%用法一样,不同点在于%匹配多个字符,而_只匹配一个字符

小结:不要过度使用通配符,如果其他操符能够达到相同的目的,应该使用其他的操作符。

   最好不要把通配符放在搜索的最开始处,这样搜索起来会比较慢。

   仔细注意通配符的位置,如果放错地方,可能不会得到你想要的结果。


第三部分;用正则表达式(regexp)进行搜索


select useranme from user where useranem like "aaa";绝对不会返回数据,like必须要跟通配符_或者%搭档,才会进行匹配,从而返回数据

select username from user where username regexp "aaa";会返回username为aaa的数据,注意跟上面的区别


select username from user where username regexp "1000|2000";返回username为1000或者2000的数据


select username from user where username regexp "[123]xxh";返回以1xxh或者2xxh或者3xxh开头的username


select username from user where username regexp "[^123]xxh";返回不是以1xxh或者2xxh或者3xxh开头的所有的username


正则表达式语法过多,具体的用到的时候再说。


第四部分:创建计算字段

 select concat(username,'(',password,')')  from user  order by username;//concat()函数拼接字符串,将username跟password连在一起显示出来

//显示出来的结果为这种形式: 2015115050450(961102)


select concat(rtrim(username),'(',rtrim(password),')') from user order by username;//rtrim()函数去掉串右边的空格


第五部分:常用函数,应该记住

AVG() 返回某列的平均值

count() 返回某列的行数

MAX() 返回某列的最大值

MIN()  返回某列的最小值

SUM()  返回某列值之和


第六部分:分组数据:

select username, count(*) as sum from user group by username;//查询username中,同样的username有多少个


select username,count(*) as aaa from user group by username HAVING count(*) >=10;//(分组过滤)查询username中,同样的username个数大于10个的


select username,count(*) as aaa from user group by username HAVING count(*) >=10 order by aaa;//在上面的基础上,加上一个排序功能









原创粉丝点击