当前位置:网站首页>SQL learning | set operation
SQL learning | set operation
2022-04-23 13:45:00 【Du Xiaorui】
Addition of tables –UNION
union Simple use , Add up the results of the two queries :
SELECT
product_id,
product_name
FROM
Product UNION
SELECT
product_id,
product_name
FROM
Product2;
- UNION It will automatically remove the duplicate data in the two query results .
- Want to make UNION Do not automatically de duplicate data , have access to UNION ALL
- When querying in the same table , Use or Often available and used union Same effect , But sometimes for efficiency reasons union. When it comes to the contents of two tables, you have to use UNION 了 .
- Use UNION When querying, columns of the same type are usually put together , But if it's a different type , You can also display two columns of different types in one column through implicit type conversion .
Cross operation –INTERSECT
mysql 8.0 Intersection operations are not supported . It is required that the intersection operation can use inner join For those .
Delivery calculation can also be used AND To achieve .
Difference set , Complement and subtraction of tables
standard SQL The subtraction operator in the table by EXCEPT, however mysql8.0 It also doesn't support . have access to not in Realization except The same effect :
-- Use NOT IN The implementation of clause exists in Product But not here. Product2 The records in the table
SELECT
*
FROM
Product
WHERE
product_id NOT IN ( SELECT product_id FROM Product2 )
Symmetry difference
Two sets A,B The symmetry difference refers to those that belong only to A Or only belong to B A collection of elements .
-- Use NOT IN Implement the difference set of two tables
SELECT
*
FROM
Product
WHERE
product_id NOT IN ( SELECT product_id FROM Product2 ) UNION
SELECT
*
FROM
Product2
WHERE
product_id NOT IN ( SELECT product_id FROM Product )
coupling
Internal connection
Connect store information and commodity information through internal connection query :
SELECT
sp.shop_id,
sp.shop_name,
sp.product_id,
p.product_name,
p.product_type,
p.sale_price,
sp.quantity
FROM
shop_product AS sp
INNER JOIN product AS p ON sp.product_id = p.product_id;
Use the sub query method to get... In the Tokyo store , The price is lower than 2000 The product information of :
SELECT
sp.shop_id,
sp.shop_name,
sp.product_id,
sp.quantity,
p.product_id,
p.product_name,
p.product_type,
p.sale_price
FROM
shop_product AS sp
INNER JOIN ( SELECT product_id, product_name, product_type, sale_price FROM product WHERE sale_price < 2000 ) AS p ON sp.product_id = p.product_id
WHERE
sp.shop_name = ' Tokyo ';
Self coupling
A table that connects itself with itself is self connection .
as follows , Find products that sell for more than the average price of such products
SELECT
P1.product_id,
P1.product_name,
P1.product_type,
P1.sale_price,
P2.avg_price
FROM
product AS P1
INNER JOIN ( SELECT product_type, AVG( sale_price ) AS avg_price FROM product GROUP BY product_type ) AS P2 ON P1.product_type = P2.product_type
WHERE
P1.sale_price > P2.avg_price;
natural join
Natural join performs equivalent inner join according to the column names contained in both tables .
SELECT
*
FROM
shop_product
NATURAL JOIN product
The above statement queries all the columns in the two tables . The common columns of the two tables are placed first .
Extraneous junction
According to which table the reserved rows are located , There are three forms of external links : Left link , Right link and all outer link .
The left link will be saved and cannot be followed in the left table ON Clause matches to the line , At this time, the rows corresponding to the right table are all missing values ; The right link will save the right table, which cannot be followed ON Clause matches to the line , At this time, the rows corresponding to the left table are all missing values ; The total external join will save two tables at the same time ON Clause matches to the line , The corresponding row in another table is filled with missing values .
The corresponding grammars of the three external links are :
-- Left link
FROM <tb_1> LEFT OUTER JOIN <tb_2> ON <condition(s)>
-- Right link
FROM <tb_1> RIGHT OUTER JOIN <tb_2> ON <condition(s)>
-- All external links
FROM <tb_1> FULL OUTER JOIN <tb_2> ON <condition(s)>
Non equivalent connection
on The connection conditions of words and sentences are not necessarily =, Including comparison operators (<,<=,>,>=, BETWEEN) And predicate operations (LIKE, IN, NOT wait ) All logical operations including can be placed in ON Clause as a join condition .
Yes Product The goods in the table are ranked according to the selling price :
SELECT
product_id,
product_name,
sale_price,
COUNT( p2_id ) AS my_rank
FROM
(
SELECT
P1.product_id,
P1.product_name,
P1.sale_price,
P2.product_id AS P2_id,
P2.product_name AS P2_name,
P2.sale_price AS P2_price
FROM
Product AS P1
LEFT OUTER JOIN Product AS P2 ON P1.sale_price <= P2.sale_price
) AS X
GROUP BY
product_id,
product_name,
sale_price
ORDER BY
my_rank;
give the result as follows :

The function of sub query is to query each commodity , Find out everything that sells for no less than it , give the result as follows :

What is used in the subquery is the non equivalent join , Find out all the products of this product that are higher than its selling price , This number is its ranking .
Cross connect –CROSS JOIN( The cartesian product )
SELECT SP.shop_id
,SP.shop_name
,SP.product_id
,P.product_name
,P.sale_price
FROM ShopProduct AS SP
CROSS JOIN Product AS P;
Use cross join Get the Cartesian product of two tables .
Homework
4.1
SELECT
*
FROM
product
WHERE
sale_price > 500 UNION
SELECT
*
FROM
product2
WHERE
sale_price > 500
4.2
SELECT
*
FROM
product
WHERE
product_id IN ( SELECT product_id FROM product2 )

4.3
SELECT
sp.product_id,
sp.shop_name,
p.product_name
FROM
shop_product AS sp
INNER JOIN (
SELECT
product_id, product_name
FROM
product AS p1
WHERE
sale_price =(
SELECT
max( sale_price )
FROM
product AS p2
WHERE
p1.product_type = p2.product_type
GROUP BY
product_type
)) AS p ON sp.product_id = p.product_id;

Use the associated sub query to find out the products with the highest selling price in each category id, And then use id As a condition of connection with shop_product Table join .
4.4
-- Internal connection mode
SELECT
p.product_type,
p.product_name,
mp.max_price
FROM
product p
INNER JOIN ( SELECT product_type, MAX( sale_price ) AS max_price FROM product GROUP BY product_type ) AS mp ON ( p.product_type = mp.product_type AND p.sale_price = mp.max_price );
-- Associated sub query method
SELECT
product_id,
product_name,
product_type
FROM
product AS p1
WHERE
sale_price =(
SELECT
max( sale_price )
FROM
product AS p2
WHERE
p1.product_type = p2.product_type
GROUP BY
product_type)
4.5
Reference material :
[1] https://github.com/datawhalechina/wonderful-sql/blob/main/ch04:%20%E9%9B%86%E5%90%88%E8%BF%90%E7%AE%97.md
版权声明
本文为[Du Xiaorui]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230556584725.html
边栏推荐
- Dolphin scheduler source package Src tar. GZ decompression problem
- Tersus notes employee information 516 MySQL query (time period uniqueness judgment of 2 fields)
- Ai21 labs | standing on the shoulders of giant frozen language models
- Zero copy technology
- PG library checks the name
- The interviewer dug a hole for me: what's the use of "/ /" in URI?
- 19c RAC steps for modifying VIP and scanip - same network segment
- Django::Did you install mysqlclient?
- Interface idempotency problem
- Detailed explanation of constraints of Oracle table
猜你喜欢

面试官给我挖坑:URI中的 “//” 有什么用?

浅谈js正则之test方法bug篇

【视频】线性回归中的贝叶斯推断与R语言预测工人工资数据|数据分享

Opening: identification of double pointer instrument panel

QT calling external program

Dynamic subset division problem

TERSUS笔记员工信息516-Mysql查询(2个字段的时间段唯一性判断)

Interface idempotency problem
![MySQL [acid + isolation level + redo log + undo log]](/img/52/7e04aeeb881c8c000cc9de82032e97.png)
MySQL [acid + isolation level + redo log + undo log]

【重心坐标插值、透视矫正插值】原理以及用法见解
随机推荐
Campus takeout system - "nongzhibang" wechat native cloud development applet
Common analog keys of ADB shell: keycode
零拷貝技術
AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
Cross carbon market and Web3 to achieve renewable transformation
【视频】线性回归中的贝叶斯推断与R语言预测工人工资数据|数据分享
Dolphin scheduler source package Src tar. GZ decompression problem
联想拯救者Y9000X 2020
SAP UI5 应用开发教程之七十二 - SAP UI5 页面路由的动画效果设置
交叉碳市场和 Web3 以实现再生变革
Analysis of the problem that the cluster component GIPC in RAC environment cannot correctly identify the heartbeat network state
MySQL [read / write lock + table lock + row lock + mvcc]
爱可可AI前沿推介 (4.23)
Lenovo Savior y9000x 2020
Oracle creates tablespaces and modifies user default tablespaces
Oracle lock table query and unlocking method
Opening: identification of double pointer instrument panel
Oracle defines self incrementing primary keys through triggers and sequences, and sets a scheduled task to insert a piece of data into the target table every second
Oracle calculates the difference between two dates in seconds, minutes, hours and days
Unified task distribution scheduling execution framework