当前位置:网站首页>Xiaobai learns MySQL - derived table
Xiaobai learns MySQL - derived table
2022-07-26 22:17:00 【bisal(Chen Liu)】
A friend recently asked this question ,MySQL one SQL Implementation plan , As shown below , Among them is PRIMARY、<derived2>、DERIVED These content , How did he and SQL Corresponding upper ?

MySQL There are indeed some and Oracle Different technical terms , But the principle and mechanism behind it are interlinked .
To illustrate , Simulate the creation of test tables ,
create table t01(
id int,
code varchar(10),
start_date datetime,
title varchar(10),
content varchar(30),
class int,
end_date datetime
); Insert some data ,
[email protected]: [test]> select * from t01;
+------+--------+---------------------+---------+------------+-------+---------------------+
| id | code | start_date | title | content | class | end_date |
+------+--------+---------------------+---------+------------+-------+---------------------+
| 1 | code1 | 2022-01-01 00:00:00 | title1 | content_1 | 1 | 2022-01-03 00:00:00 |
| 2 | code2 | 2022-01-02 00:00:00 | title2 | content_2 | 3 | 2022-01-03 00:00:00 |
| 3 | code3 | 2022-01-03 00:00:00 | title3 | content_3 | 2 | 2022-01-03 00:00:00 |
| 4 | code4 | 2022-01-04 00:00:00 | title4 | content_4 | 1 | 2022-01-06 00:00:00 |
| 5 | code5 | 2022-01-05 00:00:00 | title5 | content_5 | 1 | 2022-01-07 00:00:00 |
| 6 | code6 | 2022-01-06 00:00:00 | title6 | content_6 | 2 | 2022-01-10 00:00:00 |
| 7 | code7 | 2022-01-07 00:00:00 | title7 | content_7 | 1 | 2022-01-11 00:00:00 |
| 8 | code8 | 2022-01-08 00:00:00 | title8 | content_8 | 1 | 2022-01-12 00:00:00 |
| 9 | code9 | 2022-01-09 00:00:00 | title9 | content_9 | 3 | 2022-01-10 00:00:00 |
| 10 | code10 | 2022-01-10 00:00:00 | title10 | content_10 | 1 | 2022-01-13 00:00:00 |
+------+--------+---------------------+---------+------------+-------+---------------------+
10 rows in set (0.00 sec) The implementation is this SQL,
[email protected]: [test]>
-> select * from (
-> (select id, code, start_date, title, content, concat(' test 1:', start_date), class, end_date
-> from t01 t
-> where id=1 and code='code1' and title='title1' and start_date>='2022-01-01' and start_date<='2022-01-05'
-> order by end_date desc limit 1)
-> union all
-> (select id, code, start_date, title, content, concat(' test 2:', start_date), class, end_date
-> from t01 t
-> where id=2 and code='code2' and title='title2' and start_date>='2022-01-01' and start_date<='2022-01-05'
-> order by end_date desc limit 1)
-> union all
-> (select id, code, start_date, title, content, concat(' test 3:', start_date), class, end_date
-> from t01 t
-> where id=3 and code='code3' and title='title3' and start_date>='2022-01-01' and start_date<='2022-01-05'
-> order by end_date desc limit 1)
-> union all
-> (select id, code, start_date, title, content, concat(' test 4:', title), class, end_date
-> from t01 t
-> where id=4 and code='code4' and title='title4' and start_date>='2022-01-01' and start_date<='2022-01-05' and end_date<='2022-01-05')
-> union all
-> (select id, code, start_date, title, content, concat(' test 5:', content), class, end_date
-> from t01 t
-> where id=5 and code='code5' and title='title5' and start_date>='2022-01-01' and start_date<='2022-01-05'and end_date<='2022-01-05')
-> ) tt order by class, end_date desc;His execution plan , It is basically the same as what was mentioned at the beginning of the article ,

From the official documents , We can see , What is? Derived Tables? simply , It will be FROM The search result set appearing in the clause is treated as a table , for example FROM Medium SELECT Subquery is a derived table, And each FROM All tables in the clause need a table alias , Any from derived table The column of must have a unique name , Other requirements and examples , You can refer to the link ,
https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html
A derived table is an expression that generates a table within the scope of a query FROM clause. For example, a subquery in a SELECT statement FROM clause is a derived table:
SELECT … FROM (subquery) [AS] tbl_nameThe [AS] tbl_name clause is mandatory because every table in a FROM clause must have a name. Any columns in the derived table must have unique names
Execute the first line in the plan <derived2> This piece of " surface " It's a full table scan ,

The reason is the above SQL, Actually, it can be understood as , Yes derived table Search for , In fact, there are no search conditions ,
select * from ( ... ) tt order by class, end_date desc; In fact, carefully observe the above SQL,derived table in union all The first three connected SQL The search conditions are basically the same , and union all The last two connected SQL The search conditions are basically the same , It's just SELECT in concat The content is different , So I can rewrite .
The previous three SQL For example ,concat adopt case when Judge different id and title Under the condition of , What should be output ,where Bring all the previous fields in the condition , After the transformation, this is an independent SQL, There are no subqueries ,
[email protected]: [test]> explain
-> select id, code, start_date, content,
-> (case when id=1 and code='code1' and title='title1' then concat(' test 1:', start_date)
-> when id=2 and code='code2' and title='title2' then concat(' test 2:', start_date)
-> when id=3 and code='code3' and title='title3' then concat(' test 3:', start_date) end) c,
-> class, end_date
-> from t01
-> where id in (1, 2, 3) and title in ('title1', 'title2', 'title3')
-> and start_date>='2022-01-01' and start_date<='2022-01-05'
-> order by class, end_date desc;
+----+-------------+-------+------------+-------+---------------+------------+---------+------+------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+------------+---------+------+------+----------+----------------------------------------------------+
| 1 | SIMPLE | t01 | NULL | range | idx_t01_01 | idx_t01_01 | 5 | NULL | 3 | 10.00 | Using index condition; Using where; Using filesort |
+----+-------------+-------+------------+-------+---------------+------------+---------+------+------+----------+----------------------------------------------------+
1 row in set, 1 warning (0.00 sec)One of the optimization rules , Just do less . If rewritten as this , The biggest advantage , The same table only needs to be read once , Before derived table Each of them union all All sub queries of need to read the table once t01.
Xiaobai studies MySQL
《 Xiaobai studies MySQL - Generated Columns function 》
《 Xiaobai studies MySQL - Incremental Statistics SQL The needs of - Scheme of windowed function 》
《 Xiaobai studies MySQL - The statistical " Be opportunistic "》
《 Xiaobai studies MySQL - Incremental Statistics SQL The needs of 》
《 Xiaobai studies MySQL - You've encountered this kind of scenario where you can't log in ?》
《 Xiaobai studies MySQL - There are some differences between users created by different versions 》
《 Xiaobai studies MySQL - A tool for randomly inserting test data 》
《 Xiaobai studies MySQL - varchar Why are type fields often defined as 255?》
《 Xiaobai studies MySQL - A case of flexible index creation 》
《 Xiaobai studies MySQL - “ Be opportunistic ” The number of records in a statistical table 》
《 Xiaobai studies MySQL - Once slow SQL The positioning of 》
《 Xiaobai studies MySQL - Talk about the importance of data backup 》
《 Xiaobai studies MySQL - InnoDB Support optimize table?》
《 Xiaobai studies MySQL - table_open_cache The role of 》
《 Xiaobai studies MySQL - Table space defragmentation method 》
《 Xiaobai studies MySQL - Case sensitive problem solving 》
《 Xiaobai studies MySQL - only_full_group_by Validation rules for 》
《 Xiaobai studies MySQL - max_allowed_packet》
《 Xiaobai studies MySQL - mysqldump Parameter differences to ensure data consistency 》
《 Xiaobai studies MySQL - The query will lock the table ?》
《 Xiaobai studies MySQL - The problem of index key length limitation 》
《 Xiaobai studies MySQL - MySQL Will be affected by “ High water level ” Influence ?》
《 Xiaobai studies MySQL - Database software and initialization installation 》
《 Xiaobai studies MySQL - Chat 》
If you think this article is helpful , Please also click at the end of the article " give the thumbs-up " and " Looking at ", Or forward it directly pyq,

Recently updated articles :
《 kirin OS And Godson environment compilation and installation GreatSQL》
《 The skills to learn before going to primary school 》
《 Beijing all-weather nucleic acid testing site 》
《 Football team tour - Premier League West Ham United 》
《 Xiaobai studies MySQL - Generated Columns function 》
Recent hot articles :
《" Red Alert " Game open source code brings us a shock 》
Article classification and indexing :
边栏推荐
- 开发转测试:从零开始的6年自动化之路
- Go----Go 语言命名规范
- [tool] apifox
- Excel-vba quick start (X. prompt box, inputable pop-up box)
- 【地平线旭日X3派试用体验】+开箱帖
- [idea] tutorial on using idea shortcut keys
- OPPO 自研大规模知识图谱及其在数智工程中的应用
- Just one dependency to give swagger a new skin, which is simple and cool
- Add resource files for the project and pictures for buttons in QT
- easyui的combobox默认选中第一个选项
猜你喜欢

Schematic diagram of MOS tube

想让照片中的云飘起来?视频编辑服务一键动效3步就能实现

mysql推荐书
![[shutter -- geTx] pop up - dialog, snackBar, bottomsheet](/img/17/af2e45620e96a78235081145b7bb76.png)
[shutter -- geTx] pop up - dialog, snackBar, bottomsheet

Qt中为工程添加资源文件、给按钮添加图片

仅需一个依赖给Swagger换上新皮肤,既简单又炫酷~

Triangular wave spectrum of MATLAB excitation model

Knowledge base tools | wechat, document center, image display page can be generated by dragging (with template, directly used)

08 du 命令

Want the clouds in the picture to float? Video editing services can be achieved in three steps with one click
随机推荐
JS verify complex password
day07-
Is it safe to open an account on flush? How to choose a securities firm for opening an account
Try new functions | decrypt Doris complex data type array
My SQL is OK. Why is it still so slow? MySQL locking rules
xshell7个人免费下载,使用
ORM同时使用不同数据源和不同命名转换
In depth analysis of the source code, why is the string class immutable? (hit me before you understand)
Protobuf之proto基础语法
调试stc8a8k64d4单片机485通信总结
ORM uses different data sources and different naming transformations at the same time
小白学习MySQL - Derived Table
Triangular wave spectrum of MATLAB excitation model
同花顺手机炒股开户安全吗?怎么办理开户呢
Excel-vba quick start (XI. Common string operations)
Alibaba three sides: how to solve the problems of MQ message loss, duplication and backlog?
Get network time by unity
yolov1
Can you use redis? Then come and learn about redis protocol
伦敦银外汇走势理解与实操