当前位置:网站首页>MySQL multi table operation
MySQL multi table operation
2022-07-05 12:12:00 【ziyi813】
MySQL Multi meter operation
Multi table relation
MySQL The relationship between multiple tables can be summarized as : one-on-one , One to many / many-to-one , Many to many .
One to one relationship
- A student has only one ID card ; One ID card can only correspond to one student
- Add a unique foreign key to any table , Point to the other party's primary key , Ensure a one-to-one relationship
- see little of , If there are too many information fields in a table , Some data with low access frequency can be put into another table , Join the table and query when necessary .
One to many / many-to-one
Departments and employees :
analysis : There are many employees in a department , An employee can only correspond to one department
Principle of realization : Build foreign keys on more than one side , A primary key that points to a party of one .
Many to many relationship
Students and courses
analysis : A student can choose many courses , A course can also be chosen by many students
principle : The implementation of many to many relationship needs the help of the third line intermediate table , The middle table contains at least two fields , A many to many relationship , Split into a one to many relationship , The middle table requires at least two foreign keys , The two hour foreign keys point to the primary keys of the original two tables .
Foreign key constraints
MySQL Foreign key constraints (FOREIGN KEY) Is a special field of the table , Often used with primary key constraints . For two tables that have an association , The table where the primary key in the associated field is located is the primary table ( Parent table ), The table where the foreign key is located is the slave table ( Sub table ).
Foreign keys are used to establish the relationship between the master table and the slave table , Establish a connection between the data of two tables , Constrains the consistency and integrity of data in two tables .
characteristic :
When defining an outsourcing , The following rules need to be followed :
- The primary table must already exist in the database , Or the table that is currently being created .
- The primary key must be defined for the primary table
- Primary key cannot contain null value , But null values are allowed in foreign keys . in other words , As long as each non null value of the foreign key appears in the specified primary key , The content of this foreign key is correct .
- The number of columns in the foreign key must be the same as the number of columns in the primary key of the primary table .
- The data type of the column in the foreign key must be the same as that of the corresponding column in the primary key of the primary table .
Create foreign key constraints
The way 1: Set foreign key constraints when creating tables
stay create table In the sentence , adopt foreign key Keywords to specify foreign keys , The syntax is as follows :
[constraint < Foreign key name > foreign key Field name [ Field 2, ...] references < Main table name > Primary key column 1, [ Primary key column 2, ...] ]
Example implementation 1:
create database mydb3;
use mydb3;
-- Create department table - Main table
create table if not exists dept(
depid varchar(20) primary key, -- department ID
name varchar(20) -- Department name
);
-- Create from table , Sub table
create table if not exists emp(
eid varchar(20) primary key,
ename varchar(20),
depid varchar(20),
constraint emp_fk foreign key (depid) references dept (depid)
);
The way 2:
alter table < Data table name > add constraint < Foreign key name > foreign key(< Name >) references
Delete data
When the data of the master table is dependent on the slave table , The data in the main table cannot be deleted
The data from the table can be deleted at will
As long as the external construction is deleted , This will disassociate the master table from the slave table .
Format :
alter table < Table name > drop foreign key < Foreign key constraint name >;
Realization :
alter table emp2 drop foreign key dep_id_fk;
Many to many relationship
In many to many relationships ,A One row of the table corresponds to B Multiple lines of ,B One row of the table corresponds to A Multiple rows of the table , We want to add a new middle table , To build many to many relationships .
- Tables with foreign key columns are slave tables
- The table referenced by the foreign key column is the main table
Multi table joint query
Introduce
Multi table query is to query two or more tables at the same time , Because sometimes when users are viewing data , The data to be displayed comes from multiple tables .
Multi-table query :
Cross-join query
grammar :select * from a, b;
Internal connection query inner join --inner It can be omitted
Implicit inner join (SQL92 standard ): select * from a,b where Conditions ;
Explicit inner connection (SQL99 label ): select * from a inner join b on Conditions ;
External link query outer join --outer It can be omitted
The left outer join :left outer join
select * from A left outer join B on Conditions ;
Right connection :right outer join
select * from A right outer join B on Conditions ;
Full external connection :full outer join
select * from A full outer join B on Conditions ;
Subquery
select nesting
Table self association
Use one table as multiple tables
Cross-join query
The cross join query returns the Cartesian product of all data rows of the connected two tables .
Cartesian product can be understood as that each row of one table matches any row of another table , If A Table has M Row data ,B Table has N Row data , Then return to M*N Row data , Cartesian product will produce a lot of redundant data , Other queries in the later stage can be filtered based on the set
Format :
select * from surface 1, surface 2, surface 3,...;
Realization :
-- Without filtering criteria, all , Dikalji
select * from dep, emp;
-- department ID Query criteria
select * from dep, emp where dep.depid = emp.depid;
Internal connection query
Inner join query can be understood as taking the intersection of multiple tables
Format :
Implicit edge : select * from tableA, tableB where Conditions ;
Show inner edge : select * from tableA inner join tableB on Conditions ;
operation :
-- Query the employees of each department
-- Implicit
select * from dept, emp, where dep.depid = emp.depid;
-- Explicit
select * from dept inner join emp on dept.deptid = emp.deptid;
-- Query the data of a department
select * from dept join emp on dept.depid = emp.depid and dept.name in (' The Marketing Department ',' The administration department ');
-- The number of people querying Department data is greater than 3 The department in charge of the , And in descending order of the number of people
SELECT
a.id, a.name, count(1) as total_cnt
from dept a
join emp b on a.id = b.depid
GROUP BY
a.id, a.name
HAVING
total_cnt >= 2
order by
total_cnt desc;
Explicit operations are recommended .
External connection query
External queries are divided into left external links (left outer join), On the right outside (right outer join), Full outer join (full outer join).
outer It can be omitted , MySQL Medium full outer join I won't support it , use union.
Format :
-- The left outer join
select * from tableA left outer join tableB on < Conditions >;
-- Right connection
select * from tableA right outer join tableB on < Conditions >;
-- Full outer join
select * from tableA full outer join tableB on < Conditions >;
The operation sample :
-- External query
-- Query department employee data
SELECT * from dept left join emp on dept.id = emp.depid;
-- Query employee Department
SELECT * from dept right join emp on dept.id = emp.depid;
-- Full outer join
SELECT * from dept left join emp on dept.id = emp.depid
union
SELECT * from dept right join emp on dept.id = emp.depid;
union duplicate removal
union all No weight removal
Subquery
Subquery refers to a complete query statement , Nested several small queries with different functions , So as to complete the complex query together , Popular point is to include select Nested queries .
Subqueries usually appear in where and from clause
- where Subquery in Clause : Subqueries at this location generally return single row and single column 、 Multiple rows and columns 、 Single choice multi column data record .
- from A subquery of a clause , Subqueries at this location typically return multiple rows and columns of data records , It can be used as a temporary table .
On the premise of large amount of data , Subqueries perform better than join queries .
Example :
-- Relational query
select * from dept join emp on dept.id = emp.depid and (dept.name = ' The Marketing Department ' and age < 30 );
-- Check the marketing department , Older than 30
-- 2 Perform an association query on the results
select * from (select * from dept where `name` = ' The Marketing Department ') t1 join (select * from emp where age > 30) t2 on t1.id = t2.depid;
-- Subquery
SELECT * from emp where depid = (SELECT id from dept where `name` = ' The Marketing Department ') and age > 30;
Subquery keyword
- ALL
- ANY
- SOME
- IN,NOT IN
- EXISTS
ALL keyword
Format :
select ... from ... where c > all( Query statement );
-- Equivalent to
select ... from ... where c > result and c > result2 and c > result3 ...
characteristic :
- all Compared with all the values returned by the subquery, it is true Then return to true
- ALL Can be used in conjunction with operators
- ALL Represents the value in the specified column Must be greater than every value in the subquery set , That is, it must be greater than the maximum or minimum value of the sub query value ( Visual operation symbol )
Example :
-- Query age is less than Department ID=1003 Employee information of all ages
select * from emp where age > all( select age from emp where depid = '1003');
-- Query employee information that does not belong to any department
ANY and SOME
Format :
select ... from ... where c > any( Query statement )
-- Equivalent to
select ... from ... where c > result1 or c > result or c > result3...
characteristic :
- ANY Compare with any value returned by the subquery to true Then return to true
- ANY It can be done with =,>,>=,<,<=,<> Use a combination of
- SOME and ANY It does the same thing ,SOME It can be understood as ANY Another name for
The operation sample :
-- Query age is greater than 1003 Employee information of any employee age in the Department
select * from emp where age > any(select age from emp where depid = '1003');
IN
Format :
select ... from ... where c in ( Query statement )
-- Equivalent to
select ... from ... where c = result1 or c = result2 or c = result3 ...
characteristic :
- IN keyword , Used to determine the value of a record , Whether in the specified set
- stay INT Keywords can be preceded by NOT You can reverse the conditions
EXISTS
keyword EXISTS Is a boolean type , When the result set is returned, it is TRUE, When the result set cannot be returned, it is FALSE.
When inquiring EXISTS Use traversal method to query the appearance one by one , Each query will compare EXISTS Conditional statement , When EXISTS When the conditional statement in returns a record line, the condition is true , At this time, the current traversed record is returned , conversely , If EXISTS The conditional statement inside cannot return record lines , Then discard the currently traversed record .
Format :
select ... from ... where exists( Query statement )
边栏推荐
- 语义分割实验:Unet网络/MSRC2数据集
- vscode快捷键
- One article tells the latest and complete learning materials of flutter
- How to make your products as expensive as possible
- IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
- Hiengine: comparable to the local cloud native memory database engine
- The evolution of mobile cross platform technology
- 【云原生 | Kubernetes篇】Ingress案例实战(十三)
- Complete activity switching according to sliding
- What is the difference between canvas and SVG?
猜你喜欢
你做自动化测试为什么总是失败?
Mongodb replica set
Matlab boundarymask function (find the boundary of the divided area)
Sentinel sentinel mechanism of master automatic election in redis master-slave
【云原生 | Kubernetes篇】Ingress案例实战(十三)
Codeworks 5 questions per day (1700 average) - day 5
redis主从中的Master自动选举之Sentinel哨兵机制
[untitled]
[configuration method of win11 multi-user simultaneous login remote desktop]
调查显示传统数据安全工具在60%情况下无法抵御勒索软件攻击
随机推荐
Is investment and finance suitable for girls? What financial products can girls buy?
Riddle 1
只是巧合?苹果 iOS16 的神秘技术竟然与中国企业 5 年前产品一致!
什么是数字化存在?数字化转型要先从数字化存在开始
leetcode:1200. Minimum absolute difference
你做自动化测试为什么总是失败?
Wireless WiFi learning 8-channel transmitting remote control module
abap查表程序
【主流Nivida显卡深度学习/强化学习/AI算力汇总】
ABAP table lookup program
SENT协议译码的深入探讨
Halcon 模板匹配实战代码(一)
HiEngine:可媲美本地的云原生内存数据库引擎
JS for loop number exception
Mongodb replica set
vscode快捷键
[calculation of loss in yolov3]
Linux安装部署LAMP(Apache+MySQL+PHP)
redis主从中的Master自动选举之Sentinel哨兵机制
[yolov3 loss function]