当前位置:网站首页>Multi table query of MySQL - multi table relationship and related exercises
Multi table query of MySQL - multi table relationship and related exercises
2022-07-03 13:19:00 【Levi Bebe】
1. Multi table relation
MySQL The relationship between multiple tables can be summarized as bit : one-on-one 、 One to many or many to one 、 Many to many .


1.1 One to many foreign key constraints
1.1.1 The creation of




1.1.2 Insertion of foreign key constraints 、 Delete operation
Insert : Insert data that conforms to the format randomly in the main table , The secondary table needs to rely on the primary key column of the primary table .
Delete : When the data of the master table is dependent on the slave table , Both master and slave tables have primary keys , The primary table cannot delete the related primary key , Otherwise, you can delete ; The data from the table can be deleted at will .


1.1.3 Delete foreign key constraint key

1.2 Many to many foreign key constraints



1.3 Multi-table query

1.3.1 Cross link query

The content source of Cartesian product :

1.3.2 Internal connection query

1.3.3 External connection query

1.3.4 Multi table joint query






1.3.5 Self association query

2. Case study
Create table :
-- establish test1 database
CREATE DATABASE test1;
-- Choose to use test1 database
USE test1
-- Create department table
CREATE TABLE dept(
deptno INT PRIMARY KEY, -- Department number
dname VARCHAR(20), -- Department name
loc VARCHAR(20) -- Department Address
)
INSERT INTO dept VALUES (10,'accounting','new york');
INSERT INTO dept VALUES (20,'research','dallas');
INSERT INTO dept VALUES (30,'sales','chicago');
INSERT INTO dept VALUES (40,'operations','boston');
-- Create an employee table
CREATE TABLE emp(
empno INT PRIMARY KEY, -- Employee number
ename VARCHAR(10), -- Employee name
job VARCHAR(9), -- Staff work
mgr INT, -- Employee index leader number
hiredate date, -- Entry time
sal DOUBLE, -- Wages
comm DOUBLE, -- Bonus
deptno INT -- Corresponding dept Table foreign key
);
-- Add the main foreign key relationship between department and employee
ALTER TABLE emp ADD CONSTRAINT FOREIGN KEY emp(deptno) REFERENCES dept (deptno);
INSERT INTO emp VALUES (7369,'smith','clerk',7902,'1980-12-17',800,null,20);
INSERT INTO emp VALUES (7499,'allen','salesman',7698,'1981-02-20',1600,300,30);
INSERT INTO emp VALUES (7521,'ward','salesman',7698,'1981-02-22',1250,500,30);
INSERT INTO emp VALUES (7566,'jones','manager',7839,'1981-04-02',2975,null,20);
INSERT INTO emp VALUES (7654,'marthin','salesman',7698,'1981-09-28',1250,1400,30);
INSERT INTO emp VALUES (7698,'blake','manager',7839,'1981-05-01',2850,null,30);
INSERT INTO emp VALUES (7782,'clark','manager',7839,'1981-06-09',2450,null,10);
INSERT INTO emp VALUES (7788,'scott','analyst',7566,'1981-07-03',5000,null,20);
INSERT INTO emp VALUES (7839,'king','president',null,'1981-11-17',5000,null,10);
INSERT INTO emp VALUES (7844,'turner','salesman',7698,'1981-09-08',1500,0,30);
INSERT INTO emp VALUES (7876,'adams','clerk',7788,'1987-07-13',1100,null,20);
INSERT INTO emp VALUES (7900,'james','clerk',7698,'1981-12-03',950,null,30);
INSERT INTO emp VALUES (7902,'ford','analyst',7566,'1981-12-03',3000,null,20);
INSERT INTO emp VALUES (7934,'miller','clerk',7782,'1981-01-23',1300,null,10);
-- Create a pay scale
CREATE TABLE salgrade(
grade INT, -- Grade
losal DOUBLE, -- minimum wage
hisal double -- Maximum wage
);
INSERT INTO salgrade VALUES (1,700,1200);
INSERT INTO salgrade VALUES (2,1201,1400);
INSERT INTO salgrade VALUES (3,1401,2000);
INSERT INTO salgrade VALUES (4,2001,3000);
INSERT INTO salgrade VALUES (5,3001,9999);
practice :
-- practice
-- 1、 Return the name of the Department that owns the employee 、 Department number
SELECT DISTINCT a.dname,a.deptno FROM dept a join emp b on a.deptno=b.deptno;
-- 2、 The salary level is redundant smith Staff level
SELECT * FROM emp WHERE sal > (SELECT sal FROM emp WHERE ename = 'smith');
-- 3、 Returns the names of the employee and the manager
SELECT a.ename,b.ename FROM emp a join emp b on a.empno=b.mgr;
-- 4、 Return the name of the employee and his / her manager whose employment date is earlier than that of his / her manager .
SELECT a.ename,a.hiredate,b.ename,b.hiredate FROM emp a join emp b on a.empno=b.mgr and a.hiredate > b.hiredate;
-- 5、 Return the name of the employee and the name of his / her department .
SELECT a.ename,b.dname FROM emp a join dept b on a.deptno = b.deptno;
-- 6、 Return to work clerk The name of the employee working and the name of the Department .
SELECT a.ename,a.job,b.dname FROM emp a join dept b on a.deptno=b.deptno and job = 'clerk';
-- 7. Returns the department number and its minimum wage
SELECT deptno,MIN(sal) FROM emp GROUP BY deptno;
-- 8. Return the names of all employees in the sales department .
SELECT a.ename,b.dname FROM emp a join dept b on a.deptno=b.deptno and b.dname='sales';
-- 9. Return to employees who earn more than the average wage
SELECT ename,sal FROM emp WHERE sal > (SELECT AVG(sal) FROM emp);
-- 10、 Return to scott Employees who do the same job .
SELECT * FROM emp WHERE job = (SELECT job FROM emp WHERE ename = 'scott');
-- 11、 Return above 30 Employee information about the salary level of department employees ;
SELECT * FROM emp WHERE sal > ALL(SELECT sal FROM emp WHERE deptno=30);
-- 12、 Return to the employee's job and the minimum wage for the job ;
SELECT job,MIN(sal) FROM emp GROUP BY job;
-- 13、 Calculate the employee's annual salary , And in order of annual salary
SELECT ename,(sal * 12 + ifnull(comm,0)) as yeas_sal FROM emp ORDER BY yeas_sal DESC;
-- 14、 Return the salary of the employee whose salary is at the fourth level
SELECT * FROM emp
WHERE sal BETWEEN (SELECT losal FROM salgrade WHERE grade = 4) AND (SELECT hisal FROM salgrade WHERE grade = 4);
-- 15、 Return the name of the employee whose salary is level II 、 Department location
-- Here, three tables are combined into Cartesian product , Then use the condition to delete
SELECT
*
FROM dept a
JOIN emp b on a.deptno=b.deptno
JOIN salgrade c on grade = 2 and b.sal >= c.losal and b.sal <= c.hisal;
--------------------
SELECT
*
FROM dept a , emp b ,salgrade c
WHERE a.deptno=b.deptno
AND grade = 2 and b.sal >= c.losal and b.sal <= c.hisal;
3. Reference resources
https://www.bilibili.com/video/BV1iF411z7Pu?p=82&spm_id_from=pageDriver
边栏推荐
- Sword finger offer 11 Rotate the minimum number of the array
- Flink SQL knows why (16): dlink, a powerful tool for developing enterprises with Flink SQL
- Logseq 评测:优点、缺点、评价、学习教程
- Flink SQL knows why (19): the transformation between table and datastream (with source code)
- Luogup3694 Bangbang chorus standing in line
- Flick SQL knows why (10): everyone uses accumulate window to calculate cumulative indicators
- 【R】 [density clustering, hierarchical clustering, expectation maximization clustering]
- 35道MySQL面试必问题图解,这样也太好理解了吧
- Seven habits of highly effective people
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【第四章习题】
猜你喜欢

regular expression

我的创作纪念日:五周年
[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈..."/>开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...

8皇后问题

Sword finger offer 14- ii Cut rope II

2022-02-11 heap sorting and recursion

Detailed explanation of multithreading

mysql更新时条件为一查询

PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?

The 35 required questions in MySQL interview are illustrated, which is too easy to understand
随机推荐
The 35 required questions in MySQL interview are illustrated, which is too easy to understand
Logseq 评测:优点、缺点、评价、学习教程
Seven habits of highly effective people
C graphical tutorial (Fourth Edition)_ Chapter 20 asynchronous programming: examples - cases without asynchronous
2022-02-14 incluxdb cluster write data writetoshard parsing
The R language GT package and gtextras package gracefully and beautifully display tabular data: nflreadr package and gt of gtextras package_ plt_ The winloss function visualizes the win / loss values
[colab] [7 methods of using external data]
Elk note 24 -- replace logstash consumption log with gohangout
mysqlbetween实现选取介于两个值之间的数据范围
Finite State Machine FSM
R语言gt包和gtExtras包优雅地、漂亮地显示表格数据:nflreadr包以及gtExtras包的gt_plt_winloss函数可视化多个分组的输赢值以及内联图(inline plot)
sitesCMS v3.1.0发布,上线微信小程序
PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?
Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
2022-01-27 research on the minimum number of redis partitions
Sword finger offer 14- I. cut rope
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
对业务的一些思考
【習題五】【數據庫原理】
18W word Flink SQL God Road manual, born in the sky