hmzone 发表于 2018-10-3 07:43:26

MySQL数据库查询语句select-Spider

  1、查询表中所有字段的数据
  mysql> select * from student;
  2、指定列来查询,并且控制字段名
  mysql> select Name 姓名,Score 分数 from student;
  3、跨数据库查询,把数据库名加到表的前面即可
  mysql> select Name 姓名,Score 分数 from test.student;
  4、利用函数查询数据,ifnull(Gender,"保密")意思是查询Gender字段,有内容则输出,如果为空则显示"保密"
  mysql> select Name 姓名,Score 分数,ifnull(Gender,"保密") 性别 from test.student;
  5、查询条件
  mysql> select Name,Age,Address from student where Age=20;   //查询Name,Age,Address字段,条件为Age等于20
  mysql> select Name,Age,Address from student where Age>20;   //查询Name,Age,Address字段,条件为Age大于20
  mysql> select Name,Age,Address from student where Age20;    //查询Name,Age,Address字段,条件为Age不等于20
  6、模糊查询,以字符串为主
  mysql> select * from student where Name like "李%";      //%表示0个或多个字符串
  mysql> select * from student where Name like "_李";      //_表示一个任意字符
  mysql> select * from student where Name not like "李%";   //not like表示出了XX以外的数据
  7、between、and区间查询
  mysql> select * from student where Score between 60 and 70;    //查询分数在60-70之间的,使用以下的形式也可以查询
  mysql> select * from student where Score>=90 and Score select * from student where Score100;   //除了90-100之间的数据,以下方式也可以
  mysql> select * from student where Score not between 60 and 70;
  8、查询字段为null的数据
  mysql> select * from student where Gender is null;   //注意:此处如果写成Gender="null"是不行的
  mysql> select * from student where Gender is not null;   //is not null查询不为空的数据
  9、条件in()和not in()
  mysql> select * from student where Address in ("北京市海淀区","北京市朝阳区");      //查询Address字段为"北京市海淀区","北京市朝阳区"的数据
  mysql> select * from student where Address not in ("北京市海淀区","北京市朝阳区");   //取反
  10、查询排序
  mysql> select Name,Score from student order by Score desc;   //desc为降序,不指定默认为升序asc
  mysql> select Name,Score,Age from student order by Score desc,Gender desc;    //如果Score字段有重复的,就把重复的按照后面的条件再排序
  11、限制查询结果条数
  mysql> select * from student limit 2;    //只显示2行
  mysql> select Name,Score,Age from student order by Score asc limit 3;
  mysql> select Name,Score,Age from student where Gender="男" order by Score desc limit 1;
  mysql> select * from student order by rand() limit 2;   //rand()为随机,不推荐使用
  12、求平均值
  mysql> select avg(Score) 成绩平均值 from student;    //使用avg()函数可以求平均值
  想一下,如果有同学请假没有参加考试,那我们应不应该给他纳入到平均分的统计?答案是不能,所以在计算平均值的时候要合理的使用,字段为null时不参加avg的运算。
  13、求和函数sum()
  mysql> select sum(Score) 总分数 from student;
  14、统计查询出来数据的条数,比如统计男生多少人
  mysql> select count(*)from student where Gender="男";
  15、找出最大值max()
  mysql> select max(Score) 最高分 from student;
  16、找出最小值min()
  mysql> select min(Score) 最高分 from student;
  17、子查询
  mysql> select * from student where Score=(select max(Score) from student);   //后面的语句先执行select max(Score) from student
  18、分组查询
  比如统计男生、女生和没有填性别的人各有多少人?
  mysql> select ifnull(Gender,"保密"),count(*) 人数 from student group by Gender;
  19、查询时消除重复数据
  mysql> select distinct dept from stu;   //distinct表示消除重复

页: [1]
查看完整版本: MySQL数据库查询语句select-Spider