● 简单数据记录查询
● 条件数据记录查询
● 排序数据记录查询
● 限制数据记录查询
● 统计函数和分组数据记录查询
一: 简单数据查询
mysql> select empno,ename,job,MGR,Hiredate,sal,comm,deptno
from t_employee;
等价于
select *
from t_employee;
select empno,ename,sal
from t_employee;
还可以调整select 关键字后的字段顺序,改变字段的显示顺序
select empno,sal,ename;
from t_employee;
避免重复数据查询------DISTINCT
select distinct job
from t_employee;
实现数学四则运算数据数据查询
MYSQL支持的关系运算符:+ - * / %
>>select ename,sal*12
>> from t_employee;
>> select ename,sal*12 yearsalary
from t_employee;
使用函数CONCAT()来连接字符串,从而实现设置显示数据的格式
>>select concat(ename,'雇员的年薪为: ',sal*12) yearsalary
from t_employee;
条件数据记录查询
MYSQL支持的逻辑运算符:AND(&&) OR(||) XOR NOT(!)
MYSQL支持的关系运算符:> < = !=(<>) >= <=
SELECT field1 field2 field3...fieldn
from table_name
where CONDITION
>>select ename
from t_employee
where job='CLERK'; //在MYSQL中不区分大小写
>>select ename
from t_employee
where job='clerk' and sal>800; //and 可以 用&&替换
>> select ename
from t_employee
where sal between 1000 and 2000;
>>select ename
from t_employee
where sal not between 1000 and 2000;
>>select ename
from t_employee
where comm is not null;
等价于
>>select ename
from t_employe
where not comm is null;
>>select ename
from t_employee
where empno=7521 or empno=7782 or empno=7566 or empno=7788;
等价于
>>select ename
from t_employee
where empno in(7521,7782,7566,7788);
>>select ename
from t_employee
where empno not in (7521,7782,7566,7788);
等价于
>>select ename
from t_employee
where not empno in (7521,7782,7566,7788);
注意点:使用关键字 IN 时,查询的集合中如果存在NULL,则不会影响查询,如果使用关键字NOT IN, 查询的集合中如果存在NULL,则不会有任何的查询结果。
带LIKE关键字的模糊查询
带有“%”通配符的查询
>>select ename
from t_employee
where ename like 'A%';
>>select ename
from t_employee
where not ename like 'A%';
带有“_”通配符的查询
>>select ename
from t_employee
where ename like '_A%';
>>select ename
from t_employee
where not ename like '_A%';
等价于
>>select ename
from t_employee
where ename not like '_a%';
实现:查询字段ename中没有字母为A的数据记录
>>select ename
from t_employee
where ename not like '%A%';
等价于
where not ename like '%A%';
排序数据记录查询
MYSQL中关键字ORDER BY默认升序,所以
>>select *
from t_employee
order by sal asc;
等价于
>>select *
from t_employee
order by sal;
按照多字段排序:
>>select *
from t_employee
order by sal asc,
hiredate desc;
等价于
>>select *
from t_employee
order by sal,
hiredate desc;
限制数据记录查询数量
SELECT field1 field2 ... fieldn
FROM table_name
WHERE CONDITIN
LIMIT OFFSET_START,ROW_COUNT
如果不指定初始位置OFFSET_START,默认值是0,表示从第一条记录开始显示。
>>select *
from t_employee
where comm is null
limit 2;
>>select *
from t_employee
where comm is null
order by hiredate limit 0,5;
统计函数和分组数据记录查询
统计函数有:
COUNT()
AVG()
SUM()
MAX()
MIN()
注意:当数据值有重复才可以分组。
>>对雇员记录进行统计
>>select count(*) number
from t_employee;
>>select count(comm) number
from t_employee
where not comm=0;