当前位置:网站首页>MySQL learning record (III) multi table query, sub query, paging query, case statement, single line function
MySQL learning record (III) multi table query, sub query, paging query, case statement, single line function
2022-07-27 20:26:00 【bigdata7】
List of articles
Tips : Several statements were entered , But I don't want to execute , It can't be deleted , You need to use \c
mysql> SELECT
->
-> \c
mysql>
Multi-table query
Write the connection conditions in where Later, this method is called implicit connection , Its function is the same as that of internal connection , The belt on The connection mode of is called explicit connection . Now with the standardization and development of database , Most use explicit connection , Rarely use implicit connections .
1. Cartesian product
When multi table join query , If an invalid connection or missing connection condition is defined , Will produce Cartesian product phenomenon . The so-called Cartesian product is that each row of each table is combined with each row of other tables , Suppose the total number of rows in two tables is one x, One y, Returns the Cartesian product x*y.
2. Equivalent join query
Find the field names in the two tables are equal , Connect fields with the same data type , Will automatically go to multiple columns ( If more than one field meets the requirements , Then they will be regarded as the condition of natural connection ) Also called natural connection
The most common , It is usually carried out between tables with primary key and foreign key associations , And set the connection condition to the related column 【 Primary key - Foreign keys 】, Use ”=“ Connect related tables . Avoid Cartesian product ,n At least n-1 Equivalent connection conditions .
mysql>-- emp Employee table dept_id The fields are dept The primary key of the Department table id
mysql> desc dept;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| DEPTNO | int | NO | PRI | NULL | |
| DNAME | varchar(14) | YES | | NULL | |
| LOCATION | varchar(13) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> desc emp;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| EMPNO | int | NO | PRI | NULL | |
| ENAME | varchar(10) | YES | | NULL | |
| JOB | varchar(9) | YES | | NULL | |
| MANAGER | int | YES | | NULL | |
| HIREDATE | date | YES | | NULL | |
| SAL | double(7,2) | YES | | NULL | |
| COMM | double(7,2) | YES | | NULL | |
| DEPTNO | int | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
mysql> -- The writing method of implicit connection
mysql> select d.dname, e.empno, e.ename from dept as d, emp e where d.deptno = e.deptno;
+------------+-------+--------+
| dname | empno | ename |
+------------+-------+--------+
| RESEARCH | 7369 | SMITH |
| SALES | 7499 | ALLEN |
| SALES | 7521 | WARD |
| RESEARCH | 7566 | JONES |
| SALES | 7654 | MARTIN |
| SALES | 7698 | BLAKE |
| ACCOUNTING | 7782 | CLARK |
| RESEARCH | 7788 | SCOTT |
| ACCOUNTING | 7839 | KING |
| SALES | 7844 | TURNER |
| RESEARCH | 7876 | ADAMS |
| SALES | 7900 | JAMES |
| RESEARCH | 7902 | FORD |
| ACCOUNTING | 7934 | MILLER |
+------------+-------+--------+
14 rows in set (0.00 sec)
as Give an alias , Generally, the aliases of tables are directly separated by spaces Omit as
3. Self connect query
Query multiple tables in one table ,.
Employees and their superiors are in the employee table , use manager_id To identify employees' superiors
select e1.empno as Employee number , e1.ename as Employee name , e2.empno as Led number , e2.ename as Leader's name from emp e1, emp e2 where e1.manager_id = e2.empno;
4. Internal connection query
keyword : surface 1 inner join surface 2 on Connection condition (inner It can be omitted )
sentence :select * from a_table a inner join b_table b on a.a_id = b.b_id;
explain : Combine records from two tables , Return the records matching the associated fields , That is, return the intersection of two tables .
Self join query can also be realized by inner join :
SELECT e1.empno AS Employee number , e1.ename AS Employee name , e2.empno AS Led number , e2.ename AS Leader's name FROM emp e1 JOIN emp e2 ON e1.manager_id = e2.empno;
The condition is not necessarily that the two tables are primary and foreign key relationships , The records that meet the conditions are returned
5. External connection query
The external connection is divided into left outer join( The left outer join ) and right outer join ( Right connection ),outer It can be omitted .
keyword join The one on the left is called the left watch , The one on the right is called the right watch
a. The left connection indicates that all data of the left table is displayed , The data meeting the connection conditions in the right table , Dissatisfied use null Value padding ; Right connection indicates that all data in the right table is displayed , The data that meets the connection conditions in the left table , dissatisfaction null Value padding .
b. The result set should contain all matching rows in the right table , If some items in the right table have no corresponding items in the left table , With null Value padding .
ad locum ,join The specified table is the main table , That is, the right table is the main table .( Which table shows all rows , It's the main table )
mysql> -- The left outer join ( OUTER Keywords can be omitted )
mysql> SELECT * FROM t_class c LEFT OUTER JOIN t_major m ON c.major_id = m.id ;
+----+----------+----------+------+------------------+
| id | name | major_id | id | name |
+----+----------+----------+------+------------------+
| 1 | Software class one | 2 | 2 | Software Engineering |
| 2 | Software class two | 2 | 2 | Software Engineering |
| 3 | Class 1 of planning department | 4 | 4 | Computer science and technology |
| 4 | Class 2 of planning department | 4 | 4 | Computer science and technology |
| 5 | Excellence class | NULL | NULL | NULL |
| 6 | Dongpo class | NULL | NULL | NULL |
+----+----------+----------+------+------------------+
6 rows in set (0.00 sec)
mysql> -- Right connection ( OUTER Keywords can be omitted )
mysql> SELECT * FROM t_class c RIGHT OUTER JOIN t_major m ON c.major_id = m.id ;
+------+----------+----------+----+------------------+
| id | name | major_id | id | name |
+------+----------+----------+----+------------------+
| NULL | NULL | NULL | 5 | Information confrontation |
| NULL | NULL | NULL | 3 | Animal medicine |
| NULL | NULL | NULL | 1 | Civil Engineering |
| 3 | Class 1 of planning department | 4 | 4 | Computer science and technology |
| 4 | Class 2 of planning department | 4 | 4 | Computer science and technology |
| 1 | Software class one | 2 | 2 | Software Engineering |
| 2 | Software class two | 2 | 2 | Software Engineering |
+------+----------+----------+----+------------------+
7 rows in set (0.00 sec)
Full outer join ( MySQL I won't support it )
It is equivalent to the union of left outer and right outer connections
SELECT * FROM t_class c FULL OUTER JOIN t_major m ON c.major_id = m.id ;
Subquery
1. Single line sub query
Return single row and single column
2. Multi line sub query
Return single row and multiple columns ( Paired comparisons are used ))
3. Multi column subquery
Return multiple rows and single column
4. Correlation subquery
Subqueries use external SQL Some tables or columns of ( But outside SQL Tables and columns in subqueries cannot be used )
5. nested subqueries :
You can continue to embed subqueries inside subqueries
Paging query
Use lilmit Realize paging query
grammar :limit a , b The first parameter indicates which item to start from ( Index with pages (0 Start )* Records per page ), The second one means to check several items on one page
-- Display the first to fifth records
select * from emp limit 0,5;
CASE sentence
1. grammar :
CASE
WHEN Conditions 1 THEN result 1
WHEN Conditions 2 THEN result 2
...
WHEN Conditions n THEN result n
ELSE Other cases
END
2. Example :
mysql> SELECT s.name The student's name ,
-> c.name Course name ,
-> CASE
-> WHEN x.score BETWEEN 90 AND 100 THEN 'A'
-> WHEN x.score > 80 THEN 'B'
-> WHEN x.score > 70 THEN 'C'
-> WHEN x.score > 60 THEN 'D'
-> ELSE 'E'
-> END AS Grades
-> FROM t_students s
-> JOIN t_scores x ON x.sid = s.id
-> JOIN t_courses c ON x.cid = c.id ;
+--------------+--------------+--------------+
| The student's name | Course name | Grades |
+--------------+--------------+--------------+
| zhang wuji | C++ | A |
| zhang wuji | C++ | A |
| Zhou Zhiruo | C++ | A |
| Zhang Sanfeng | C++ | A |
| Liu Shumei | C++ | E |
| Liu Shumei | C++ | E |
| zhang wuji | Java | A |
| Small zhao | Java | A |
| Wu Mochou | Java | D |
| Zhao Min | Oracle | B |
| Zhang Sanfeng | Oracle | E |
| Zhou Zhiruo | HTML/CSS | A |
| Wu Mochou | HTML/CSS | C |
| Liu Shumei | HTML/CSS | E |
+--------------+--------------+--------------+
14 rows in set (0.00 sec)
One line function
SQL Function is the built-in function of the database , It can be applied to SQL Statement to achieve specific functions , The single line function calculates the data of each line and gets a line of output ; A multi line function is a function in which multiple lines of data participate in the operation to obtain a line of output .
1. Character functions
length()、 concat()、upper() 、lower()、substr() or substring()、 instr()、trim()、lpad() and rpad()、replace() ;
Case conversion function :upper,lower
mysql> SELECT upper('abc'), lower('ABC');
+--------------+--------------+
| upper('abc') | lower('ABC') |
+--------------+--------------+
| ABC | abc |
+--------------+--------------+
1 row in set (0.00 sec)
String concatenation function :concat
Connection string
mysql> SELECT concat('tx', 'sql');
+---------------------+
| concat('tx', 'sql') |
+---------------------+
| txsql |
+---------------------+
1 row in set (0.00 sec)
Get substring function :substr
Used for string interception The first parameter is the truncated string The second parameter is the number of bits to intercept Space is also a character
mysql> SELECT substr('java sql js', 5);
+--------------------------+
| substr('java sql js', 5) |
+--------------------------+
| sql js |
+--------------------------+
1 row in set (0.00 sec)
Other string functions :
length( character string );: Gets the length of the stringinstr(' The parent string ', ' Substring ');: Get the index of the substring in the parent string from 1 Start The space is also calledltrim(' java web');: Remove the space to the left of the stringrtrim('java web ');: Remove the space on the righttrim(' java web ');: Remove the spaces on both sidesreplace(' character string ', ' Substring to replace ', ' Replace string ');: The first is the parent string The second substring to replace Replaced string
2. Mathematical functions
round()、ceil() and floor()、truncate()、mod();
round(x, [y]): For the specified X Perform rounding operations You can specify the number of reserved digits y It can be negativetruncate(x, y): For the specified X Intercept operation , You can specify the number of digits to be reservedceil(x): Return no less than the specified value x Minimum integer of such as x yes 4.5 return 5floor(x): Return is no greater than x Maximum integer for such as x yes 8.1 return 8abs(x): Take the absolute valuemod(x, y): take x Divide y The remainder ofsign(x): take x Symbolic function of negative (-1),0, Positive numbers (1)power(x, y): take x Of y The next power x=2 ,y=3, be 2 Of 3 The second power equals 8sqrt(x): take x The square root of
3. Date function
now()、curdate()、curtime()、 year 、 month 、 Japan 、 Hours 、 minute 、 second 、str_to_date() and date_format();
The current date function
Date interception function
Date increasing function
special case :
Date formatter
1. Concept :
Formatter is a format symbol that describes the date , Use letters to describe specific parts of the date , With % start , for example %m Represents the month in the date .
2. Formatter table :
| Format | describe |
|---|---|
| %a | Abbreviated week name |
| %b | Abbreviated month name |
| %c | month , The number |
| %D | Days of the month with English prefix |
| %d | Day of the month , The number (00-31) |
| %e | Day of the month , The number (0-31) |
| %f | Microsecond |
| %H | Hours (00-23) |
| %h | Hours (01-12) |
| %I | Hours (01-12) |
| %i | minute , The number (00-59) |
| %j | Days of (001-366) |
| %k | Hours (0-23) |
| %l | Hours (1-12) |
| %M | Month name |
| %m | month , The number (00-12) |
| %p | AM or PM |
| %r | Time ,12- Hours (hh:mm:ss AM or PM) |
| %S | second (00-59) |
| %s | second (00-59) |
| %T | Time , 24- Hours (hh:mm:ss) |
| %U | Zhou (00-53) Sunday is the first day of the week |
| %u | Zhou (00-53) Monday is the first day of the week |
| %V | Zhou (01-53) Sunday is the first day of the week , And %X Use |
| %v | Zhou (01-53) Monday is the first day of the week , And %x Use |
| %W | Week name |
| %w | Days of the week (0= Sunday , 6= Saturday ) |
| %X | year , Sunday is the first day of the week ,4 position , And %V Use |
| %x | year , Monday is the first day of the week ,4 position , And %v Use |
| %Y | year ,4 position |
| %y | year ,2 position |
Query today
/*
NOW() Function returns the current date and time .
TO_DAYS() Function returns the date and year 0( date "0000-00-00") Days between .
*/
SELECT * FROM cpidata WHERE TO_DAYS( Time field name ) = TO_DAYS(NOW());
Check yesterday
/*
NOW() Function returns the current date and time .
TO_DAYS() Function returns the date and year 0( date "0000-00-00") Days between .
*/
SELECT * FROM Table name WHERE TO_DAYS( NOW( ) ) - TO_DAYS( Time field name ) = 1
Check this week
/*
YEARWEEK() Return year and week
DATE_FORMAT( Formatted date , Format symbol ) Date format function
*/
SELECT * FROM Table name WHERE YEARWEEK(DATE_FORMAT( Date field name ,'%Y-%m-%d')) = YEARWEEK(NOW());
Query last week
/*
YEARWEEK() Return year and week
DATE_FORMAT( Formatted date , Format symbol ) Date format function
*/
SELECT * FROM Table name WHERE YEARWEEK(DATE_FORMAT( Date field name ,'%Y-%m-%d')) = YEARWEEK(NOW())-1;
Query near 7 God
/*
DATE_SUB() Function to subtract a specified time interval from a date
DATE_SUB( Legal date expression ,INTERVAL The interval you want to add Time type )
CURDATE() Function returns the current date .
*/
SELECT * FROM Table name where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date( Time field name )
Query near 30 God
/*
DATE_SUB() Function to subtract a specified time interval from a date
DATE_SUB( Legal date expression ,INTERVAL The interval you want to add Time type )
CURDATE() Function returns the current date .
*/
SELECT * FROM Table name where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date( Time field name )
Inquire about this month
/*
DATE_FORMAT( Formatted date , Format symbol ) Date format function
*/
SELECT * FROM Table name WHERE DATE_FORMAT( Time field name , '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' );
Query last month
/*
PERIOD_DIFF( First date , Second date ) Function returns the difference between two dates . The results are calculated in months
*/
SELECT * FROM Table name WHERE PERIOD_DIFF( DATE_FORMAT( NOW( ) , '%Y%m' ) , DATE_FORMAT( Time field name , '%Y%m' ) ) =1
Query this quarter
/*
QUARTER( date ) Returns the quarter of the date :
*/
SELECT * FROM Table name WHERE QUARTER( Date field name )=QUARTER(NOW());
Query last quarter
/*
QUARTER( date ) Returns the quarter of the date :
DATE_SUB() Function to subtract a specified time interval from a date
DATE_SUB( Legal date expression ,INTERVAL The interval you want to add Time type )
*/
SELECT * FROM Table name WHERE QUARTER( Date field name )=QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER));
Query current year
/*
year( Date field name ) Returns the year in the date
*/
SELECT * FROM Table name WHERE YEAR( Date field name )=YEAR(NOW());
Query last year
/*
year( Date field name ) Returns the year in the date
DATE_SUB() Function to subtract a specified time interval from a date
DATE_SUB( Legal date expression ,INTERVAL The interval you want to add Time type )
*/
SELECT * FROM Table name WHERE YEAR( Date field name )=YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR));
4. Other built-in system functions
version()、database()、user();
边栏推荐
- Assignment 1 - Hello World ! - Simple thread Creation
- Western digital mobile hard disk can't be read (the idiom of peace of mind)
- 同源与跨域
- 十年测试老鸟聊聊移动端兼容性测试
- 想转行软件测试,先过这三关,包含一份3000字超全测试学习指南
- Pyqt5 rapid development and practice 4.3 qlabel and 4.4 text box controls
- PyQt5快速开发与实战 4.3 QLabel and 4.4 文本框类控件
- 2019年全球半导体营收同比下滑12%,中国市场份额第一
- 数仓搭建——DWD层
- Clickhouse implements materializedpostgresql
猜你喜欢

PyQt5快速开发与实战 4.5 按钮类控件 and 4.6 QComboBox(下拉列表框)

想转行软件测试,先过这三关,包含一份3000字超全测试学习指南

Technology sharing | how to do Assertion Verification in interface automated testing?

JS realizes video recording - Take cesium as an example

图解LeetCode——剑指 Offer II 115. 重建序列(难度:中等)

Online judge output overrun

MLX90640 红外热成像仪测温传感器模块开发笔记(七)

Standing on the shoulders of giants to learn, jd.com's popular architect growth manual was launched

多点双向重发布及路由策略的简单应用

办公自动化解决方案——DocuWare Cloud 将应用程序和流程迁移到云端的完整的解决方案
随机推荐
Unified Modeling Language (UML) specification
Slf4j introduction
MediaTek releases Helio g80, a mid-range game phone chip
数仓搭建——DWD层
内置函数时间日期函数
图解LeetCode——剑指 Offer II 115. 重建序列(难度:中等)
ZJNU 22-07-26 比赛心得
预处理与宏定义
Add joint control to gltf model
What does bus mean
C语言--数组
PC Museum (3) MITs Altair 8800
西数移动硬盘无法读取(高枕无忧的成语)
OA项目之我的审批(查询&会议签字)
Chapter 3 basic operation
Huawei's mobile phone shipments exceed Apple's, ranking second in the world, but it faces a large amount of inventory that needs to be cleaned up
图解LeetCode——592. 分数加减运算(难度:中等)
[RCTF2015]EasySQL-1|SQL注入
我也是醉了,Eureka 延迟注册还有这个坑
Leetcode exercise 2 - sum of two numbers