1、查询所有
select * from 表名;
2、指定查询
select 列名1,列表2... from 表名;
3、条件查询
条件查询就是在查询时给出WHERE子句,在WHERE子句中可以使用一些运算符及关键字
select * from student where name = 'zs';
where 后面可以跟运算符以及关键字
=(等于)、!=(不等于)、<>(不等于)、<(小于)、<=(小于等于)、>(大于)、>=(大于等于);
BETWEEN…AND;值在什么范围
IN(set);
固定的范围值
IS NULL;(为空) IS NOT NULL(不为空)
AND;与
OR;或
NOT; 非
查询性别为男,并且年龄为20的学生记录
select * from student where gender = '男' and age = 20;
查询学号为1001 或者姓名为zs的记录
select * from student sno = 1001 or name = 'zs';
查询学号为1001,1002,1003的记录
select * from student where sno = 1001 or sno = 1002 or sno = 1003;
select * fron student where sno in(1001,1002,1003);
select * from student where sno not in(1001,1002,1003);
查询年龄为null的记录
select * from student where age is null;
查询年龄在18到20之间的学生记录
selete * from student where age >= 18 and age <=20;
selete * from student where age between 18 and 20;
查询性别非男的学生记录
select * from student where gender != '男';
查询姓名不为null的学生记录
select * from student where name is not null;
4、模糊查询
根据指定的关键进行查询
_ :任意一个字符
%:任意0~n个字符
使用
查询姓名由5个字母构成的学生记录
select * from student where name like '_____';
模糊查询必须使用LIKE关键字。其中 “_”匹配任意一个字母,5个“_”表示5个任意字母。
查询姓名由5个字母构成,并且第5个字母为“s”的学生记录
select * from student where name like '_____s%';
查询姓名以“m”开头的学生记录
SELECT * FROM students WHERE name LIKE 'm%';
其中“%”匹配0~n个任何字母。
查询姓名中第2个字母为“u”的学生记录
select * from student where name like '_u%';
查询姓名中包含“s”字母的学生记录
select * from student where name like '%s%';
字段控制查询
去除重复记录
SELECT DISTINCT name FROM students;
把查询字段的结果进行运算,必须都要是数据型
SELECT *,字段1+字段2 FROM 表名;
列有很多记录的值为NULL,
因为任何东西与NULL相加结果还是NULL,所以结算结果可能会出现NULL。
下面使用了把NULL转换成数值0的函数IFNULL:
SELECT *,age+IFNULL(score,0) FROM students;
对查询结果起别名
在上面查询中出现列名为sx+IFNULL(yw,0),这很不美观,现在我们给这一列给出一个别名,为total:
SELECT *, yw+IFNULL(sx,0) AS total FROM score;
省略 AS SELECT *, yw+IFNULL(sx,0) total FROM score;**
5、对查询的结果进行排序
使用
对所有员工的薪水进行排序
select * from employee order by salary asc;
查询所有学生记录,按年龄降序排序
select * from employee order by age desc;
查询所有雇员,按月薪降序排序,如果月薪相同时,按编号升序排序
SELECT * FROM employee ORDER BY salary DESC, id ASC;
6、聚合函数
对查询的结果进行统计计算
常用聚合函数
COUNT():统计指定列不为NULL的记录行数;
MAX():计算指定列的最大值,如果指定列是字符串类型,那么使用字符串排序运算;
MIN():计算指定列的最小值,如果指定列是字符串类型,那么使用字符串排序运算;
SUM():计算指定列的数值和,如果指定列类型不是数值类型,那么计算结果为0;
AVG():计算指定列的平均值,如果指定列类型不是数值类型,那么计算结果为0;
使用
COUNT
查询employee表中记录数:
select count(*) as total_count from employee;
查询员工表中有绩效的人数
slect count(performance) from employee;
查询员工表中月薪大于2500的人数:
select cout(*) from employee where salary > 2500;
统计月薪与绩效之和大于5000元的人数:
select COUNT(*) from employee where salary+IFNULL(performance,0) > 5000;
查询有绩效的人数,和有管理费的人数:
select COUNT(performance), COUNT(manage) from employee;
SUM和AVG
查询所有雇员月薪和:
select SUM(salary) from employee;
查询所有雇员月薪和,以及所有雇员绩效和
select SUM(salary),SUM(performance) from employee;
查询所有雇员月薪+绩效和:
select SUM(salary+IFNULL(performance,0)) from employee;
统计所有员工平均工资:
select AVG(salary) from employee;
MAX和MIN
查询最高工资和最低工资:
select MAX(salary), MIN(salary) from employee;