首页 > 代码库 > mysql单表查询

mysql单表查询

 简单查询:

    select * from tb_name

    select field1,field2 from tb_name;

    select * from tb_name where qualification ; 

    

例子:select  name,age from students where age+1>20; 

         select name from student where age>20 and gender=‘M‘;

         select name from student where age>20 or gender=‘M‘;

         select name from student where not age>20 and not gender=‘M‘;

         select name from student where not (age>20 or gender=‘M‘);

         select name from student where age>=20 and age<=50;或者select name from student where age between 20 and 25;

         select name from student where like name ‘Y%‘;

         

        

        

         REGEXP 或者RLIKE 后面可以跟上正则表达式:

         

         

               select name from student where name relike ‘^[MNY].*$‘;匹配以M或者N或者Y开头后面任意字符的。

               

               

               

               IN的用法:年龄在18、20、25岁的同学名字

               

               

               select name from student where age in (18,20,25);

               

               显示student表中cid是null的同学;

                     select name from student where cid is null;

                     

                     

                     不是null值的写法:

                     select name from student where cid is not null;

                     

  根据查询到的数据排序:

                       select name from student where cid is not null order by name;

                       

     数据存储的三种格式:堆文件、顺序文件、hash

     

     给字段取别名;

    select name as student_name from student where cid is not null order by name;

    

限制显示的行数(limit);

    例子: select name as student_name from student as xiaohai  limit 2

    限制只显示两行。

    

    略过前两行:

     select name as student_name from student as xiaohai limit 2,3

     略过前两行显示三行。

     

     聚合计算:

     

     所有同学的平均年龄:

        select avg(age) from student;

        select max(age) from student;

        select min(age) from student;  

        select sum(age) from student; 求和

        select count(age) from student;   求个数

        

  group by :分组

  

  select age,gender from student group by gender;

  按照性别把student表分组(即男,女) 显示age gender

  

  select avg(age) from student group by gender;

  

  按照性别把表student分组,分别计算出他们的的平均值。

  

  分组的主要目的是聚合:

                   

  注意:对group by 条件进行过滤必须用having 它的作用相当于where

  

  select count(cid1) as persons,cid from student group by cid1 having persons>=2;

   having的作用是对group by的结果做再次过滤


本文出自 “wangconggao” 博客,请务必保留此出处http://wangconggao.blog.51cto.com/3253868/1579692

mysql单表查询