SELECT DISTINCT * FROM 表名;
DESC 表名;
SELECT CONCAT('列名1', ',', '列名2') FROM 表名;
SELECT 列名 AS 重命名 FROM 表名;
SELECT IFNULL(列名, 如果为null显示的值) FROM 表名;
# 查询员工名中包含字符a的员工信息
SELECT * FROM employees WHERE last_name LIKE '%a%';
# 查询员工名中第二个字符为_的员工名
SELECT last_name FROM employees WHERE last_name LIKE '_$_%' ESCAPE '$';
SELECT DATEDIFF(MAX(hiredate), MIN(hiredate)) DIFFERENCE FROM employees;
# 查询哪个部门的员工个数>2
SELECT COUNT(*) , department_id FROM employees GROUP BY department_id HAVING COUNT(*)>2;
按年代分类:
按功能分类:
夺标等值连接的结果为多表的交集部分
n表连接,至少需要n-1个条件
# 查询女神名和对应的男神名
SELECT `NAME`, boyName
FROM boys, beauty
WHERE beauty.boyfriend_id=boys.id;
# 为表起别名
# 查询员工名、工种号、工种名
SELECT last_name, e.job_id, job_title
FROM employees e, jobs j
WHERE e.job_id=j.job_id;
# 查询员工的工资和工资级别
SELECT salary, grade_level
FROM employees e, job_grades g
WHERE salary BETWEEN g.lowest_sal AND g.highest_sal;
# 查询员工名和上级的名称
SELECT e.employee_id, e.last_name, m.employee_id, m.last_name
FROM employees e, employees m
WHERE e.manager_id=m.employee_id;
语法:
select 查询列表
from 表1 别名
【连接类型】join 表2 别名
on 连接条件
【where 筛选条件】
分类:
inner可以省略
# 查询员工名、部门名
SELECT last_name, department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;
# 三表连接
# 查询员工名、部门名、工种名,并按部门名降序
SELECT last_name, department_name, job_title
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id
INNER JOIN jobs j ON e.job_id = j.job_id
ORDER BY department_name DESC;
# 查询员工的工资级别
SELECT salary, grade_level
FROM employees e
INNER JOIN job_grades g
ON e.salary BETWEEN g.lowest_sal AND g.highest_sal;
# 查询员工名字、上级名字
SELECT e.last_name, e.last_name
FROM employees e
INNER JOIN employees m
ON e.manager_id = m.employee_id;