当前位置:网站首页>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
边栏推荐
- Annotation and reflection
- Convolution emotion analysis task4
- Server coding bug
- PostgreSQL installation
- stm32和电机开发(从mcu到架构设计)
- Task6: using transformer for emotion analysis
- JSP and filter
- Flick SQL knows why (10): everyone uses accumulate window to calculate cumulative indicators
- Detailed explanation of multithreading
- Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)
猜你喜欢
MySQL constraints
Sword finger offer 12 Path in matrix
Introduction to the implementation principle of rxjs observable filter operator
18W word Flink SQL God Road manual, born in the sky
File uploading and email sending
2022-02-09 survey of incluxdb cluster
Flink SQL knows why (XI): weight removal is not only count distinct, but also powerful duplication
February 14, 2022, incluxdb survey - mind map
高效能人士的七个习惯
有限状态机FSM
随机推荐
Road construction issues
2022-02-14 incluxdb cluster write data writetoshard parsing
2022-02-09 survey of incluxdb cluster
C graphical tutorial (Fourth Edition)_ Chapter 20 asynchronous programming: examples - cases without asynchronous
剑指 Offer 16. 数值的整数次方
regular expression
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter 6 exercises]
MapReduce实现矩阵乘法–实现代码
正则表达式
Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
2022-01-27 redis cluster technology research
Flink code is written like this. It's strange that the window can be triggered (bad programming habits)
Image component in ETS development mode of openharmony application development
Cadre de logback
Mysqlbetween implementation selects the data range between two values
Reptile
mysql更新时条件为一查询
Sitescms v3.0.2 release, upgrade jfinal and other dependencies
【历史上的今天】7 月 3 日:人体工程学标准法案;消费电子领域先驱诞生;育碧发布 Uplay
Understanding of CPU buffer line