当前位置:网站首页>MySQL 04 advanced query (II)
MySQL 04 advanced query (II)
2022-07-27 18:54:00 【A sea of clouds, a first thought】
MySQL 04 Advanced query ( Two )
List of articles
- MySQL 04 Advanced query ( Two )
One 、 Learning goals
- master IN Usage of subquery
- master EXISTS Subquery
- Master the use principles and precautions of sub query
- Able to use SQL Conduct comprehensive query
Two 、 Subquery replacement table connection
problem :
- The query in “2020-01-02” I did it this day “ Urine routine ” List of patients for this examination
Use a variety of methods to realize query
Method 1 : Use table connection
- perform prescription、patient and checkitem Three watches JOIN operation , Then screen the list of patients according to the conditions
Use JOIN Keyword implementation
SELECT patientName FROM patient pa INNER JOIN prescription pre ON pa.patientID = pre.patientID INNER JOIN checkitem c ON pre.checkItemID = c.checkItemID WHERE c.checkItemName = ' Urine routine ' AND pre.examDate = '2020-01-02';Use WHERE Clause realization
SELECT patientName FROM patient pa,prescription pre, checkitem c WHERE pa.patientID = pre.patientID AND pre.checkItemID = c.checkItemID AND c.checkItemName = ' Urine routine ' AND pre.examDate = '2020-01-02';Mode two : Use sub query to realize patient information screening of review conditions
Realize the idea :
- Inquire about checkitem surface , get “ Urine routine ” Inspection item number of
- According to the inspection item number , stay prescription The query in the table is “2020-01-02” The number of patients who had this examination on this day
- According to the patient number in patient Look up the patient's name in the table
SELECT patientName FROM patient WHERE patientID = (SELECT patientID FROM prescription WHERE checkItemID = (SELECT checkItemID FROM checkitem WHERE checkItemName = ' Urine routine ') AND examDate = '2020-01-02');Summary and analysis :
- Subquery is more flexible 、 convenient , It is often used as a screening condition for addition, deletion, modification and query , Suitable for manipulation A table of data
- Table connection change Suitable for see Multi table data
3、 ... and 、IN Subquery
problem :
- If processing a subquery returns multiple records ?
analysis :
- Use IN Subquery
grammar :
- IN The syntax of the subquery
SELECT …… FROM Table name WHERE Field name IN ( Subquery );3.1. Subquery returns multiple result examples :
The query in “2020-03-02” done “ blood fat 、 Blood glucose test ” List of patients for this examination
SELECT patientName FROM patient WHERE patientID = (SELECT patientID FROM prescription WHERE checkItemID = (SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ') AND examDate = '2020-03-02');Running results
- resolvent : Use IN Subquery
3.2.IN Subquery example 1
Commonly used IN Replace the equal sign operator (=) Subquery of
IN Subsequent subqueries can return multiple records
#in: It limits the screening range of patient number , And subsequent sub queries can return multiple records SELECT patientName FROM patient WHERE patientID IN (SELECT patientID FROM prescription WHERE checkItemID = (SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ') AND examDate = '2020-03-02');3.3.in Subquery example 2
problem :
- The query was made in the last time “ blood fat 、 Blood glucose test ” Names of all patients who have seen the disease in the Department examined 、 Gender 、 Date of birth and address
Realize the idea :
- get “ blood fat 、 Blood glucose test ” The inspection item number of this inspection
- Query the latest inspection date according to the obtained inspection item number
- According to the obtained item number and the latest inspection date , Inquire the department number
- Query the number of all patients who have seen diseases in these departments according to the department number
- Be careful : The department number obtained may be multiple records
- Query the name of the patient according to the patient number 、 Gender 、 Date of birth and address
#1. get “ blood fat 、 Blood glucose test ” The inspection item number of this inspection SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test '; #2. Query the latest inspection date according to the obtained inspection item number SELECT MAX(examDate) FROM prescription WHERE checkItemID=( SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test '); #3. According to the obtained item number and the latest inspection date , Inquire the department number SELECT depID FROM prescription WHERE examDate=( SELECT MAX(examDate) FROM prescription WHERE checkItemID=( SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ')) AND checkItemID = ( SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test '); #4. Query the number of all patients who have seen diseases in these departments according to the department number SELECT patientID FROM prescription WHERE depID IN ( SELECT depID FROM prescription WHERE examDate = ( SELECT MAX(examDate) FROM prescription WHERE checkItemID = ( SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ' ) ) AND checkItemID = ( SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ' ) ) #5. Query the name of the patient according to the patient number 、 Gender 、 Date of birth and address SELECT patientName, gender, birthDate, address FROM patient WHERE patientID IN ( SELECT patientID FROM prescription WHERE depID IN ( SELECT depID FROM prescription WHERE examDate = ( SELECT MAX(examDate) FROM prescription WHERE checkItemID = ( SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ' ) ) AND checkItemID = ( SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ' ) ) );
Four 、NOT IN Subquery
problem :
The query was made in the last time “ blood fat 、 Blood glucose test ” Names of all patients who have seen the disease in other departments except the Department examined 、 Gender 、 Date of birth and address
analysis :
Realize the idea :
- get “ blood fat 、 Blood glucose test ” The inspection item number of this inspection
- Query the latest inspection date according to the obtained inspection item number
- According to the obtained item number and the latest inspection date , Inquire the department number
- Query the number of all patients who have seen diseases in other departments except these departments according to the department number
- Query the name of the patient according to the patient number 、 Gender 、 Date of birth and address
SELECT patientName, gender, birthDate, address FROM patient WHERE patientID IN ( #4. Query the number of patients who have seen diseases in other departments SELECT patientID FROM prescription WHERE depID NOT IN ( #3. Inquire the department number SELECT depID FROM prescription WHERE examDate=( #2. Query the latest inspection date according to the inspection item number SELECT MAX(examDate) FROM prescription WHERE checkItemID=( #1. get “ blood fat 、 Blood glucose test ” Check item number SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ' ) ) AND checkItemID = ( #1. get “ blood fat 、 Blood glucose test ” Check item number SELECT checkItemID FROM checkitem WHERE checkItemName = ' blood fat 、 Blood glucose test ' ) ) );
5、 ... and 、EXISTS Subquery
problem :
How to use SQL Statement detection log Whether the table has been created ?
DROP TABLE IF EXISTS log; CREATE TABLE IF NOT EXISTS log ( … … # Omit the table creation statement );EXISTS Whether there are other uses of keywords ?
- EXISTS Subquery
grammar :
SELECT …… FROM Table name WHERE EXISTS ( Subquery );
- Subqueries have returned results : EXISTS The subquery result is TRUE
- The subquery returns no results : EXISTS The subquery result is FALSE, The outer query does not execute
Example :
demand :
- Find out if any patients have done “ blood fat 、 Blood glucose test ”
- If there is , Please display the name of the patient who has undergone this examination 、 Gender 、 Age 、 Inspection date and results
analysis :
- Use EXISTS Subquery to find out whether any patients have done “ blood fat 、 Blood glucose test ”
- If a patient has done “ blood fat 、 Blood glucose test ”, from patient Table and prescription Query the name of the patient who has done this examination in the table 、 Gender 、 Age 、 Inspection date and results
- Use EXISTS Subquery can detect whether there are records that meet the query criteria. If there are , Then query the corresponding records that meet the requirements according to the business logic
# Query patient information and examination information , The patient's age is calculated according to the date of birth SELECT patientName, gender, FLOOR(DATEDIFF(CURDATE(),birthDate)/365) AS age FROM patient # Use EXISTS Clause to determine whether it has been done “ blood fat 、 Blood glucose test ” Patients WHERE EXISTS( SELECT patientID FROM prescription WHERE checkItemID = ( SELECT checkItemID FROM checkitem WHERE checkItemName=' blood fat 、 Blood glucose test ') AND patient.patientID = prescription.patientID);
- and IN Like subqueries ,EXISTS Subqueries can also be added NOT Keyword implements the opposite operation
- NOT EXISTS It means that there is no record in the result set and it returns true, Otherwise return to false!
6、 ... and 、NOT EXISTS Subquery
problem :
- Inquire patients “ Li Siyu ” Have you ever done it “ Coagulation five ” Check
- If I haven't done it , Then insert a record
- With “ internal medicine ” In the name of today, give her a “ Coagulation five ” The inspection of
analysis :
- You can use NOT EXISTS Subquery detection “ Li Siyu ” Have you ever done it “ Coagulation five ” Check
- If NOT EXIST The execution result of the subquery returns true, Then perform data insertion
INSERT INTO prescription(patientID,depID,examDate,checkItemID) SELECT patientID, 3 as depID, CURDATE() as examDate, 4 as checkItemID FROM patient WHERE NOT EXISTS (SELECT patientID FROM prescription WHERE checkItemID = ( SELECT checkItemID FROM checkitem WHERE checkItemName=' Coagulation five ') AND patient.patientID = prescription.patientID) AND patientName=' Li Siyu ';
7、 ... and 、 Sub query summary
- What is subquery ?
- When one query is a condition of another , It's called a subquery
- Subqueries can appear in SQL Where is the statement ?
- Subqueries can be used wherever expressions are allowed
- Nested in parent query SELECT Subquery of statement , May include
- SELECT Clause
- FROM Clause
- WHERE Clause
- GROUP BY Clause
- HAVING Clause
8、 ... and 、 Sub query considerations
- Usually , Place subqueries to the right of the comparison criteria to increase readability
- Subqueries can return single or multiple rows of data , At this point, choose the appropriate keyword
- When the sub query returns single row data , Comparison operators can be used in comparison conditions
- When the sub query returns multiple rows of data , You need to use IN or NOT IN keyword
- If you decide whether there is data returned from the sub query , Need to use EXISTS or NOT EXISTS keyword
- Only appear in subqueries 、 Columns that do not appear in the parent query cannot be included in the output column
Nine 、 Summary of this chapter
边栏推荐
- Bathroom with demister vanity mirror touch chip-dlt8t10s
- idea 2020.1社区版下载体验
- Hash、Set、List、Zset、BitMap、Scan
- 迷你洗衣机触摸芯片-DLT8MA12TS-杰力科创
- 阿里架构师耗时280个小时整理的1015页分布式全栈小册,轻松入手分布式系统
- Quick access to website media resources
- 内网的公司邮箱服务器怎么发外部邮件
- Must the MySQL query column be consistent with the group by field?
- Interviewer: what do you think is your biggest weakness?
- Wechat applet obtains openid, sessionkey, unionid
猜你喜欢

Idea 2020.1 Community Edition download experience

Wechat applet obtains openid, sessionkey, unionid

建木持续集成平台v2.5.2发布

What does the number of network request interface layers (2/3 layers) mean

nacos显示服务注册地址错误

Netred RGB mirror light touch chip-dlt8s15b-jericho

Matplotlib(基本用法)

Whole body multifunctional massage instrument chip-dltap602sd

图文结合,完美解释MySQL逻辑备份的实现流程

连接查询和子查询
随机推荐
低噪负离子风扇触摸IC
Conflict between blur event and click event in input box
JDBC-MySql 01 JDBC操作MySql(增删改查)
阿里架构师耗时280个小时整理的1015页分布式全栈小册,轻松入手分布式系统
内网的公司邮箱服务器怎么发外部邮件
Uni app for wechat login (to be finished)
这样的API网关查询接口优化,我是被迫的
百度地图技术概述,及基本API与WebApi的应用开发
Overview of Baidu map technology, and application development of basic API and webapi
商品评论信息与评论信息分类
全自动吸奶器芯片-DLTAP703SD
Interviewer: what do you think is your biggest weakness?
浅谈JVM(面试常考)
LeetCode 刷题 第三天
Whole body multifunctional massage instrument chip-dltap602sd
Join query and subquery
Jianmu continuous integration platform v2.5.2 release
RuntimeError: output with shape [1, 256, 256] doesn‘t match the broadcast shape [3, 256, 256]【报错】
js中的函数与DOM获取元素和事件属性的使用
Wechat applet wechat payment overview


