MySQL ---- SQL语句学习笔记三

2021-09-07 16:34:47 浏览数 (1)

实例用表

  1. emp表

id

name

salary

depId

1

Joe

70000

1

2

Henry

80000

2

3

Sam

60000

2

4

Max

90000

1

代码语言:javascript复制
CREATE TABLE emp(id INT,name char(255),salary int, depId int);

INSERT INTO emp VALUES(1,'Joe',70000,1),(2,'Henry',80000,2),(3,'Sam',60000,2),(4,'Max',90000,1);
  1. dep表

id

name

1

IT

2

Sales

代码语言:javascript复制
CREATE TABLE dep(id INT,name char(255));

INSERT INTO dep VALUES(1,'IT'),(2,'Sales');

1.WHERE 里边的子查询

子查询如果在 where 或 select 中时,相当于【子查询】先计算结果再判断! “=” 的子查询返回必须唯一,否则就会报错! IN 的子查询可以返回一列的结果!

1.1 找出每个部门工资最高的员工!

代码语言:javascript复制
SELECT
	dep. NAME AS '部门',
	p2. NAME AS '员工',
	p2.salary
FROM
	emp p2
JOIN dep ON dep.id = p2.depId
WHERE
	p2.salary IN (
		SELECT
			MAX(salary) AS salary
		FROM
			emp p1
		GROUP BY
			p1.depId
	)

2.SELECT 里边的子查询

子查询返回必须唯一!否则就会报错!

2.1 找出全部员工中工资最高的,添加max行!

代码语言:javascript复制
SELECT
	dep. NAME,
	p2. NAME,
	p2.salary,
	(
		SELECT
			MAX(salary) AS salary
		FROM
			emp p1
	) AS max
FROM
	emp p2
JOIN dep ON dep.id = p2.depId

3.having 里边的子查询

不常见,基本不用!

4.ON 里边的子查询

不常见,基本不用!

5.FROM 里边的子查询

在 FROM 里边的子查询必须要有别名!

5.1 找出每个部门工资最高的员工!

代码语言:javascript复制
SELECT
	dep. NAME AS '部门',
	p2. NAME AS '员工',
	p2.salary
FROM
	emp p2
JOIN dep ON dep.id = p2.depId
JOIN (
	SELECT
		MAX(salary) AS salary,
		depId
	FROM
		emp p1
	GROUP BY
		p1.depId
) p3 ON p2.depId = p3.depId
AND p2.salary = p3.salary

6.半连接查询

子查询中使用了父查询的信息!

6.1 找出每个部门工资最高的员工!

代码语言:javascript复制
SELECT
	dep. NAME AS '部门',
	p1. NAME AS '员工',
	p1.salary
FROM
	emp p1
JOIN dep ON dep.id = p1.depId
WHERE
	p1.salary = (
		SELECT
			MAX(salary) AS max
		FROM
			emp p2
		WHERE
			p2.depId = p1.depId
	)

0 人点赞