当前位置:网站首页>Data query of MySQL (multi table query)
Data query of MySQL (multi table query)
2022-07-29 02:16:00 【Yu'an.112】
1、FROM Clause
SELECT The query object of is FROM Clause assignment .
Grammar format :FROM Table name 1 [ [ AS ] Alias 1] [, Table name 2 [ [ AS ] Alias 2 ] ] | JOIN Clause
FROM Clause can reference a table in two ways , The first way is to use USE Statement to make a database the current database , In this case , If in FROM Clause to specify the table name , Then the table should belong to the current database . The second method is to specify the name of the database to which the table belongs before the table name .
for example , Suppose the current database is db1, Now I want to display the database db2 The watch in tb The content of , Then use the statement :
SELECT * FROM db2.tb;
stay SELECT When specifying the column name after the keyword, you can also bring the name of the database and table before the column name , But in general , If the selected field is unique in each table , There is no need to specify .
example : from Members Retrieve the information of all customers in the table , And use table aliases Users
SELECT * FROM Members AS Users
2、 Multiple table joins
To query data in different tables , Must be in FROM Clause specifies multiple tables . Combining data from different columns into a table is called table join . for example , stay Bookstore You need to find the order in the database “ Web programming ” The name of the book's member and the number of orders , You need to Book、Members and Sell this 3 Connect tables , To find the result
2.1、 Full connection
Full join refers to crossing each row of each table with each row of other tables to produce all possible combinations , Column contains all the columns that appear in the table , Cartesian product . for example , surface 1 Yes 3 That's ok , surface 2 Yes 2 That's ok , Then they are all connected to the table 3 Yes 3x2=6 That's ok .
2.2、 Internal connection
The table obtained by full join produces a very large number of rows , The number of rows obtained is the product of the number of rows in each table , And the data in the table generated by full connection is meaningless in most cases . In this situation , Conditions are usually set to reduce the result set to meaningful tables , Such a connection is called inner connection . If the set condition is equivalent , It's also called equivalent connection .
2.3、 External connection
The outer connection includes the left outer connection (LEFT OUTER JOIN) And right outer connection (RIGHT OUTER JOIN) Two kinds of
The left outer join : In addition to matching rows in the result table , It also includes rows in the left table that do not match in the right table , For such a line , The selected column from the right table is set to NULL.
Right connection : In addition to matching rows in the result table , It also includes rows in the right table that do not match in the left table , For such a line , The selected column from the left table is set to NULL.
if FROM Separate the tables with commas in the clause , It specifies the full connection , The table obtained by full join produces a very large number of rows
example : lookup Bookstore The titles of books ordered by customers in the database 、 Number of copies ordered and order time
SELECT Book. Title ,Sell. Number of copies ordered ,Sell. Order time
FROM Book,Sell
WHERE Book. Book number =Sell. Book number ;3、 JOIN Connect
Use JOIN Keyword when establishing multi table connection ,JOIN Clause defines how to use JOIN Keyword connection table
Grammar format :
Table name 1 INNER JOIN Table name 2
| Table name 1 {LEFT | RIGHT} [ OUTER ] JOIN Table name 2
ON Connection condition | USING( Name )
Appoint INNER The connection of keywords is inner connection . The inner connection is in FROM Clause to produce intermediate results ON The result obtained after the condition . Internal connection is the default of the system , It can be omitted INNER keyword . After using the inner connection ,FROM clause ON Conditions are mainly used to connect tables , Other conditions that do not belong to the join table can be used WHERE Clause to specify .
example : lookup Bookstore The titles of books ordered by customers in the database 、 Number of copies ordered and order time
SELECT Book. Title ,Sell. Number of copies ordered ,Sell. Order time
FROM Book INNER JOIN Sell
ON(Book. Book number =Sell. Book number );example : Look up and buy “ Web programming ” And the order quantity is greater than 5 Book information of this
SELECT Title , Number of copies ordered
FROM Book JOIN Sell
ON Book. Book number =Sell. Book number
WHERE Title =' Web programming ' AND Number of copies ordered >5;example : Look up and buy “ Web programming ” And the order quantity is greater than 5 Ben's book 、 Member name and subscription number
SELECT Book. Book number , Membership name , Title , Number of copies ordered
FROM Sell JOIN Book ON Book. Book number =Sell. Book number
JOIN Members ON Sell. ID number =Members. ID number
WHERE Title =' Web programming ' AND Number of copies ordered >5;As an exception , You can connect a table to itself , It's called self connect . To find a row with the same column value in a table , You can use self connect . When using self join, you need to specify two aliases for the table , And references to all columns must be qualified with aliases .
example : lookup Bookstore Database Sell The orders in the table are different 、 Order number of books with the same book number 、 Book number and number of ordered copies
SELECT a. The order number ,a. Book number ,a. Number of copies ordered
FROM Sell AS a JOIN Sell AS b
ON a. Book number =b. Book number AND a. The order number !=b. The order number ;If the table to be connected has the same column name , And the connection condition is that the column names are equal , be ON The condition can also be changed into USING Clause .USING(column_list) Clause is used to name a series of columns . These columns must exist in both tables . among column_list For the same column names in the two tables .
Appoint OUTER The connection of keywords is external connection .
example : Find the book number of all books 、 Quantity and ID number number of the member who ordered the books , If you have never ordered , We should also include the situation .
SELECT Book. Book number ,Book. Number , ID number
FROM Book LEFT OUTER JOIN Sell
ON Book. Book number =Sell. Book number ;If not used LEFT OUTER JOIN, The result will not include the information of books that have not been ordered . After using the left outer connection , The row returned in the result contains information about books that have not been ordered , The ID number field value of the corresponding line is NULL.
4、 Subquery
In the query condition , You can use the result of another query as part of the condition . for example , Determine whether the column value is equal to the value in the result set of a query , Queries that are part of the query criteria are called subqueries .SQL The standard allows SELECT Use multiple nesting , Used to represent complex queries . Subqueries can be used in addition to SELECT In the sentence , It can also be used in INSERT、UPDATE And DELETE In the sentence . Subqueries are usually associated with IN、EXIST Predicates and comparison operators are used in combination .
4.1、IN Subquery
IN Sub query is used to judge whether a given value is in the sub query result set .
Grammar format : expression [ NOT ] IN ( Subquery )
example : Find in Bookstore Zhang San's order information in the database
Ideas : Containing order information Sell The table does not contain the name of the customer , Only the customer's ID number . To find Zhang San's order information , First you need to know Zhang San's ID number . Therefore, we must first Members Look up Zhang San's ID number in the table , Then query the order information according to the ID number .
SELECT *
FROM Sell
WHERE ID number IN
(SELECT ID number FROM Members WHERE Membership name =' Zhang San ');4.2、 Compare subqueries
This subquery can be considered as IN Extension of subquery , It compares the value of the expression with the result of the subquery
Grammar format : expression {< | <= | = | > | >= | != | <>}{ALL | SOME | ANY}( Subquery )
If the result set of the subquery returns only one row of data , You can compare directly through comparison operators . If the result set of the subquery returns multiple rows of data , Need to use {ALL | SOME | ANY} To limit
ALL Specifies that the expression is to be compared with each value in the subquery result set , When each value of the expression satisfies the comparison relationship , To return to true, Otherwise return to false
SOME And ANY Synonyms , It means that as long as the expression meets the comparison relationship with a value in the sub query result set , Just go back to true, Otherwise return to false
example : Find the purchased book number “IS-01” Membership information of books
SELECT * FROM Members WHERE ID number =ANY
(SELECT ID number FROM Sell WHERE Book number ='IS-01');4.3、EXISTS Subquery
EXISTS Predicates are used to test whether the result of a subquery is an empty table , If the result set of the subquery is not empty , be EXISTS return true, Otherwise return to false.EXISTS And NOT Use a combination of , namely NOT EXISTS, Its return value is the same as EXISTS Just the opposite .
Grammar format :[ NOT ]EXISTS ( Subquery )
example : Find every order 10 Names of members of the above books
SELECT Membership name FROM Members WHERE EXISTS
(SELECT * FROM Sell WHERE ID number =Members. ID number and Number of copies ordered >10);边栏推荐
- h5背景音乐通过触摸自动播放
- 2022.7.27-----leetcode.592
- 全志T3/A40i工业核心板,4核[email protected],国产化率达100%
- druid. io kill -9 index_ Realtime traceability task
- Promise解决异步
- Understand the working principle of timer in STM32 in simple terms
- Internet of things development -- mqtt message server emqx
- Monadic linear function perceptron: Rosenblatt perceptron
- 【云原生与5G】微服务加持5G核心网
- MySQL安装常见报错处理大全
猜你喜欢

数学建模——带相变材料的低温防护服御寒仿真模拟

TI C6000 TMS320C6678 DSP+ Zynq-7045的PS + PL异构多核案例开发手册(2)

Excel 打开包含汉字的 csv 文件出现乱码该怎么办?
![[circuit design] convert AC AC to DC](/img/b4/67df7f4555379c63694e89055499bb.jpg)
[circuit design] convert AC AC to DC

Anti crawler mechanism solution: JS code generates random strings locally

Type analysis of demultiplexer (demultiplexer)

指针——黄金阶段

Mathematical modeling -- bus scheduling optimization

JetPack--Navigation实现页面跳转
[electronic components] zener diode
随机推荐
(arxiv-2018) 重新审视基于视频的 Person ReID 的时间建模
Internet of things development -- mqtt message server emqx
Cookies and sessions
Mathematical modeling -- Optimization of picking in warehouse
[UE4] replay game playback for ue4.26
Read the recent trends of okaleido tiger and tap the value and potential behind it
年中总结 | 与自己对话,活在当下,每走一步都算数
弹性布局 单选
JS dom2 and dom3
iVX低代码平台系列详解 -- 概述篇(二)
(cvpr-2019) selective kernel network
一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力
【RT学习笔记1】RT-Thread外设例程——控制Led灯闪烁
The number of consecutive subarrays whose leetcode/ product is less than k
leetcode/和大于等于target的连续最短子数组
"Activity recommendation" rush rush! 2022 international open source Festival has new content
费曼学习法(符号表)
忽略微信设置字体
Comprehensive analysis of news capture doorway
Control the pop-up window and no pop-up window of the input box