1 基本select语句
//查询table中的所有字段名称
select * from table;
//查询table中的某个字段名称
select column from table;
//查询table中的字段,对其进行去重处理
select distinct column from table;
列的别名(新的名字)
//紧跟列的方式,可给别名加双引号“ ”
select column 列名1 from table;
//加as作为说明的方式,可给别名加双引号“ ”
select column as 列名1 from table;
字符串可以是select列表中的一个字符,数字,日期
日期和字符只能在单引号出现‘ ’
2 过滤和排序数据
使用where子句,产生限制条件
select column from table where condition(s);
select employee_id,last_name,job_id,department_id
from employees
where department_id=90;
3.比较运算
操作符
= 表示等于。
> 表示大于
>= 大于、等于
< 小于
<= 小于、等于
<> 不等于 !=
赋值使用 :=符号
select last_name,salary from employees where salary<=300;
其它比较运算
操作符
between ... and 表示在两个值之间
in(set) 等于值列表中的一个或多个
Like 模糊查询
is null 空值
between的小例子:
select last_name,salary from employeer where salary between 230 and 1599;
in的小例子:
select employee_id,last_name,salary,manager_id
from employees
where manager_id in(100,101,201);//查询manager_id中含有100,101,201的字段。
like的小例子:
使用Like运算选择类似的值
选择条件可以包含字符或数字
% 代表零个或多个字符(任意个字符)
select first_name from employees where first_name like 'S%';
'%'和'_'可同时使用
NULL
使用is(not) null来判断空值
select last_name,manager_id from employees
where manager_id is null;
逻辑运算
and 逻辑并
or 逻辑或
not 逻辑否
And要求并的关系为真,都满足
selecy employee_id,last_name,job_id,salary
from employees
where salary>1000 and job_id like '%MAN';
Or要求或关系为真,满足其中一个条件就行
selecy employee_id,last_name,job_id,salary
from employees
where salary>1000 or job_id like '%MAN';
Not
select last_name,job_id
from employees
where job_id Not in('s','s1');
order by子句/数据库默认升序排序
使用order by子句排序
ASC(ascend):升序
DESC(descend):降序
可按别名排序
select employee_id,last_name,salary*12 annual
from employees order by annual;
多个列排序
按照order by列表的顺序排序
select last_name,department_id,salary
from employees
order by department_id,salary desc;(先前在往后)
4 多表查询
select table1.字段1,table2.字段2
from table1,table2.
这样子会产生笛卡尔集。
比如table1有21行,table2有22行,就会产生
21*22行的数据
避免笛卡尔集的最好方法就是加where条件去限制
Mysql连接
使用连接在多个表中查询数据
select table1.column,table2.column
from table1,table2
where table1.column1=table2.column2;
在where子句中写入连接的条件
在表中有相同列时,在列名之前加上表名前缀
区分重复的列名
* 使用表名前缀在多个表中区分相同的列
* 在不同表中具有相同列名的列可用表的别名来区分
表的别名
使用别名可以简化查询
使用表名前缀可以提高执行效率
select e.employee_id,e.last_name,e.department_id,d.department_id,d.location_id;
from employees e,departments d
where e.department_id=d.department_id;
连接多个表的情况。
连接n个表,至少需要n-1个连接条件
select e.last_name,d.department_name,loc.city
from employees e,departments d,locations loc
where e.department_id=d.department_id and d.location_id=loc.location_id;
SQL99:使用on子句来创建连接
可以使用on子句指定额外的连接条件
select e.employee_id,e.last_name,e.department_id,d.department_id,d.location_id
from employees e join departments d
on (e.department_id=d.department_id);
使用on子句来创建多表连接
select employee_id,city,department_name
from employees e
select e.last_name,d.department_name,loc.city
from employees e
join departments d,
on e.department_id=d.department_id
join location loc
on d.location_id=loc.location_id;