|
SQL学习总结:
星期一考试了,从小到大,大大小小的考试经历不止百次了。可这次考试,心里还是有有点紧张。今晚精力旺盛,顺便理理头绪,复习复习。
我们学习SQL课程总共4天,重点是SQL的DML(Data Manipulation Language)语句。老师说以后我们用到更多的主要就是这些语句。现在总结如下:
一、查询语句(SELECT)
1、一般用法:
SELECT Column
FROM Table;
例1:
--从员工表里,选择姓名和工资
SELECT last_name, salary
FROM employees;
例2:
--从员工表里,选择姓名和邮件,并将两列数据合成一列,以"员工邮件"为列名显示
SELECT last_name + ' 的电子邮件是: ' + last_name + [email=]'@testage.com'[/email] AS "员工电子邮件详细信息"
FROM employees;
2、过滤重复行:
SELECT DISTINCT Column
FROM Table;
例:
--统计员工表里的工种分为几类
SELECT DISTINCT job_id
FROM employees;
3、增加选择条件:
SELECT Column
FROM Table
WHERE condition;
例1:
--从员工表里,选择工资高于5000的员工
SELECT last_name, salary
FROM employees
WHERE salary > 5000;
例2:
--从员工表里,选择工资高于5000,并且属于80号部门的员工
SELECT last_name, salary, department_id
FROM employees
WHERE salary > 5000 AND department_id = 80;
例3:
--从员工表里,选择工资高于8000,或者属于80号部门的员工
SELECT last_name, department_id, salary 高于8000或者属于80号部门的员工
FROM employees
WHERE salary > 8000 OR department_id = 80;
例4:
--从员工表里,选择年薪低于36000,并且没有奖金的员工信息
SELECT salary*12 年薪, *
FROM employees
WHERE salary*12 < 3000*12 AND commission_pct IS NULL;
例5:
--从员工表里,选择工资在3000到5000之间(包含3000和5000)的员工信息
SELECT *
FROM employees
WHERE salary BETWEEN 3000 AND 5000;
例6:
--从员工表里,选择属于20号部门,30号部门,80号部门的员工
SELECT last_name, department_id
FROM employees
WHERE department_id IN(20, 30, 80);--另一种写法:WHERE department_id = 20 OR department_id = 30 OR department_id = 80;
例7:
--从员工表里,选择不属于20,30,80号部门的员工
SELECT last_name, department_id
FROM employees
WHERE department_id NOT IN(20, 30, 80);
4、模糊查询:
SELECT Column
FROM Table
WHERE keywords LIKE %_;
例1:
--从员工表里,选择姓名以B打头的所有员工信息
SELECT *
FROM employees
WHERE last_name LIKE 'B%';
例2:
--从员工表里,选择姓名第二个字母是a的所有员工信息
SELECT *
FROM employees
WHERE last_name LIKE '_a%';
例3:
--从员工表里,选择姓名以A或B或C打头的员工信息
SELECT *
FROM employees
WHERE last_name LIKE '[A-C]%';
5、多表查询:
SELECT Table1.Column, Table2.Column
FROM Table1, Table2
WHERE Condition;
例1:
--查询员工表里,所有员工所属的部门名字
SELECT employees.last_name, department.department_name
FROM employees, department
WHERE employees.department_id = department.department_id;
例2:
--查询查询工资高于8000的员工所属的部门
SELECT e.last_name, e.salary, d.department_name
FROM employees e
INNER JOIN department d
ON e.salary > 8000 AND e.department_id = d.department_id;
例3:
--查询所有员工所属的部门,即使该员工没有被分配任何部门
SELECT e.last_name, d.department_name
FROM employees e
LEFT OUTER JOIN department d
ON e.department_id = d.department_id;
例4:
--查询每个部门所属的员工,即使该部门没有任何员工
SELECT d.department_name, e.last_name
FROM employees e
RIGHT OUTER JOIN department d
ON e.department_id = d.department_id;
例5:
--查询所有部门以及所有员工,即使该部门没有任何员工或该员工没被分配任何部门
SELECT e.last_name, d.department_name
FROM employees e
FULL OUTER JOIN department d
ON e.department_id = d.department_id;
例6:
--查询员工Baida的经理是谁
SELECT e.last_name 雇员, m.last_name 经理
FROM employees e, employees m
WHERE e.manager_id = m.employee_id
AND e.last_name = 'Baida'; |
|