数据库查询语句

简单查询:select 字段名 from 表名 where 条件  例:select name,age from student where sex=”女”  # 查询所有女生的姓名和年龄  注:select 后面跟‘*’时表示查询符合条件的所有数据

Distinct 过滤重复行:select distinct 字段名 from 表名 , 例:select name,age from student  #显示student中的姓名和年龄,但重复的数据只显示一次。注:数据去重也可以使用分组来进行

 模糊匹配(查询符合条件的所有数据): 例:select name,age,sex from student where name like %”  #查询student表中所有姓王的人的姓名、年龄和性别。注:“%” 匹配任意个字符,”_”匹配单个字符,“[]”区间,如[1,2,3,4]。

聚合函数:

求平均值:AVG ,例:select age from student where sex=”男”  #求学生表中男生的平均年龄。

总和:sum,例:select sum(English) from student      #求学生表中的英语成绩的总和

最小(大)值:min(max)  select name,age from student #求学生表中年龄最小(大)的人的姓名和年龄

计数统计:count ,例:select name count(grade) from student where name=”张三”   #统计学生表中张三的成绩数量

Group by 子句(分组):select AVG(age) from student group By sex   #按性别分组查询学生表中的平均年龄

Having 子句: 例:select name,grade from student group grade having grade >70   # 查询学生表中成绩大于70的学生姓名和成绩。

Order by(排序)子句:例:select * from student order By grade DESC(ASC)  # 按成绩从高到低(从低到高)排列显示所有数据。注 :DESC表示从高到低,可以省略,AES表示从低到高。

Limit 子句(截取):例:select * from student limit 2,4  #取出第3条到低6条数据,2表示下标为2的数据,即第3条;4表示取4条数据,即取到第6条。

嵌套查询(将一个查询语句作为另一个查询语句的条件):例:select * from student where sex=(select sex from student where name=”张三”  #查询与学生张三性别相同的所有学生的数据。

联接查询:select  student.username,student.userID,score.name,score.userID from student left(right) join score score on student.userID=score.userID  #查询两张表格的数据,以左(右)边的表的数据为准,左(右)边表的数据会全部显示出来,右(左)边表的数据符合条件的会显示,不符合的显示为空。

  欢迎大家批评指正,找出问题,谢谢!

原文地址:https://www.cnblogs.com/yhcTACK/p/14967534.html