当前位置:网站首页>[sql] usage of self connection
[sql] usage of self connection
2022-07-26 02:57:00 【wy_ hhxx】
《SQL Advanced tutorial 》 MICK 1-2 Usage of self connection
About... For creating tables for examples SQL Statements and sample code , Please refer to the following website .
http://www.ituring.com.cn/book/1813( Please click on “ Download with book ” Download relevant materials in Chinese )
---------------------------------------------------------------
explain : The tests in the following notes are based on postgresql14
Command line connection local PSQL: psql -U <username> -d <dbname> -h 127.0.0.1 -W
Catalog
Rearrangeable 、 array 、 Combine
Method 1 : Use the extremum function
Method 2 : Use non equivalent connection
Find locally inconsistent columns
Rearrangeable 、 array 、 Combine
Products Create table statement
CREATE TABLE Products
(name VARCHAR(16) PRIMARY KEY,
price INTEGER NOT NULL);
-- Rearrangeable · array · Combine
INSERT INTO Products VALUES(' Apple ', 50);
INSERT INTO Products VALUES(' a mandarin orange ', 100);
INSERT INTO Products VALUES(' Banana ', 80);
==========================================
test=> select * from Products
test-> ;
name | price
------+-------
Apple | 50
a mandarin orange | 100
Banana | 80
(3 rows)
test=>
A join to the same table is called “ Self join ”(self join)
(1) Rearrangeable
test=> SELECT P1.name AS name_1, P2.name AS name_2
test-> FROM Products P1, Products P2;
name_1 | name_2
--------+--------
Apple | Apple
Apple | a mandarin orange
Apple | Banana
a mandarin orange | Apple
a mandarin orange | a mandarin orange
a mandarin orange | Banana
Banana | Apple
Banana | a mandarin orange
Banana | Banana
(9 rows)
test=>
(2) array
Remove pairs made of the same elements , for example ( Apple , Apple )
test=> SELECT P1.name AS name_1, P2.name AS name_2
test-> FROM Products P1, Products P2
test-> WHERE P1.name <> P2.name;
name_1 | name_2
--------+--------
Apple | a mandarin orange
Apple | Banana
a mandarin orange | Apple
a mandarin orange | Banana
Banana | Apple
Banana | a mandarin orange
(6 rows)
test=>
(3) Combine
test=> SELECT P1.name AS name_1, P2.name AS name_2
test-> FROM Products P1, Products P2
test-> WHERE P1.name > P2.name;
name_1 | name_2
--------+--------
Apple | a mandarin orange
Banana | a mandarin orange
Banana | Apple
(3 rows)
test=>
Delete duplicate lines

The reconstruction Products
test=> DROP TABLE Products;
DROP TABLE
test=>
test=> CREATE TABLE Products
test-> (rowid INTEGER PRIMARY KEY,
test(> name VARCHAR(16),
test(> price INTEGER NOT NULL);
CREATE TABLE
test=>
test=> INSERT INTO Products VALUES(1, ' Apple ',50);
INSERT 0 1
test=> INSERT INTO Products VALUES(2, ' a mandarin orange ',100);
INSERT 0 1
test=> INSERT INTO Products VALUES(3, ' a mandarin orange ',100);
INSERT 0 1
test=> INSERT INTO Products VALUES(4, ' a mandarin orange ',100);
INSERT 0 1
test=> INSERT INTO Products VALUES(5, ' Banana ',80);
INSERT 0 1
test=>
test=> SELECT * FROM Products;
rowid | name | price
-------+------+-------
1 | Apple | 50
2 | a mandarin orange | 100
3 | a mandarin orange | 100
4 | a mandarin orange | 100
5 | Banana | 80
(5 rows)
test=>Use the associated subquery to delete duplicate rows
Method 1 : Use the extremum function
test=> DELETE FROM Products P1
test-> WHERE rowid < ( SELECT MAX(P2.rowid)
test(> FROM Products P2
test(> WHERE P1.name = P2. name
test(> AND P1.price = P2.price ) ;
DELETE 2
test=>
test=> SELECT * FROM Products;
rowid | name | price
-------+------+-------
1 | Apple | 50
4 | a mandarin orange | 100
5 | Banana | 80
(3 rows)
test=>
Method 2 : Use non equivalent connection
test=> DELETE FROM Products P1
test-> WHERE EXISTS ( SELECT *
test(> FROM Products P2
test(> WHERE P1.name = P2.name
test(> AND P1.price = P2.price
test(> AND P1.rowid < P2.rowid );
DELETE 2
test=> SELECT * FROM Products;
rowid | name | price
-------+------+-------
1 | Apple | 50
4 | a mandarin orange | 100
5 | Banana | 80
(3 rows)
test=>
Find locally inconsistent columns
【 example 】 Suppose there is such an address table , The primary key is the person's name , The same family ID equally

If the family ID equally , The address must also be the same , It can be said that Mr. and Mrs. Maeda are like this “ Records of the same family with different addresses ” It's a hand error , Non equivalent self connection can be used to find such records
Addresses Create table statement
-- Find locally inconsistent columns
CREATE TABLE Addresses
(name VARCHAR(32),
family_id INTEGER,
address VARCHAR(32),
PRIMARY KEY(name, family_id));
INSERT INTO Addresses VALUES(' Maeda Yiming ', '100', ' Tiger gate, Tokyo Metropolitan port area 3-2-29');
INSERT INTO Addresses VALUES(' Maeda Youmei ', '100', ' Tiger gate, Tokyo Metropolitan port area 3-2-92');
INSERT INTO Addresses VALUES(' Kato tea ', '200', ' West Shinjuku, Shinjuku District, Tokyo 2-8-1');
INSERT INTO Addresses VALUES(' Kato Sheng ', '200', ' West Shinjuku, Shinjuku District, Tokyo 2-8-1');
INSERT INTO Addresses VALUES(' Sherlock Holmes ', '300', ' Baker Street 221B');
INSERT INTO Addresses VALUES(' Watson ', '400', ' Baker Street 221B');
Find records with the same family but different addresses
test=> select * from Addresses;
name | family_id | address
----------+-----------+-------------------------
Maeda Yiming | 100 | Tiger gate, Tokyo Metropolitan port area 3-2-29
Maeda Youmei | 100 | Tiger gate, Tokyo Metropolitan port area 3-2-92
Kato tea | 200 | West Shinjuku, Shinjuku District, Tokyo 2-8-1
Kato Sheng | 200 | West Shinjuku, Shinjuku District, Tokyo 2-8-1
Sherlock Holmes | 300 | Baker Street 221B
Watson | 400 | Baker Street 221B
(6 rows)
test=>
test=> SELECT DISTINCT A1.name, A1.address
test-> FROM Addresses A1, Addresses A2
test-> WHERE A1.family_id = A2.family_id
test-> AND A1.address <> A2.address ;
name | address
----------+------------------------
Maeda Yiming | Tiger gate, Tokyo Metropolitan port area 3-2-29
Maeda Youmei | Tiger gate, Tokyo Metropolitan port area 3-2-92
(2 rows)
test=>【 example 】 Use non equivalent self connection to find Products Goods with the same price in
test=> DROP TABLE Products;
DROP TABLE
test=> CREATE TABLE Products
test-> (name VARCHAR(16) PRIMARY KEY,
test(> price INTEGER NOT NULL);
CREATE TABLE
test=> DELETE FROM Products;
DELETE 0
test=> INSERT INTO Products VALUES(' Apple ',50);
INSERT 0 1
test=> INSERT INTO Products VALUES(' a mandarin orange ',100);
INSERT 0 1
test=> INSERT INTO Products VALUES(' grapes ',50);
INSERT 0 1
test=> INSERT INTO Products VALUES(' watermelon ',80);
INSERT 0 1
test=> INSERT INTO Products VALUES(' lemon ',30);
INSERT 0 1
test=> INSERT INTO Products VALUES(' Banana ',50);
INSERT 0 1
test=>
test=> SELECT * FROM Products
test-> ;
name | price
------+-------
Apple | 50
a mandarin orange | 100
grapes | 50
watermelon | 80
lemon | 30
Banana | 50
(6 rows)
test=> SELECT DISTINCT P1.name, P1.price
test-> FROM Products P1, Products P2
test-> WHERE P1.price = P2.price
test-> AND P1.name <> P2.name;
name | price
------+-------
Banana | 50
Apple | 50
grapes | 50
(3 rows)
test=>
Sort
【 example 】 Set the table according to the price from high to low Products Sort the goods in . We make the same order of goods with the same price , And then their products have two sorting methods , One is to skip the next position , The other is not to skip the next position .
test=> SELECT name, price,
test-> RANK() OVER (ORDER BY price DESC) AS rank_1,
test-> DENSE_RANK() OVER (ORDER BY price DESC) AS rank_2
test-> FROM Products;
name | price | rank_1 | rank_2
------+-------+--------+--------
a mandarin orange | 100 | 1 | 1
watermelon | 80 | 2 | 2
Apple | 50 | 3 | 3
grapes | 50 | 3 | 3
Banana | 50 | 3 | 3
lemon | 30 | 6 | 4
(6 rows)
test=>
【 example 】 Do not rely on sorting function implementation , If the same order has appeared , Then skip the next position
test=> SELECT P1.name,
test-> P1.price,
test-> (SELECT COUNT(P2.price)
test(> FROM Products P2
test(> WHERE P2.price > P1.price) + 1 AS rank_1
test-> FROM Products P1
test-> ORDER BY rank_1;
name | price | rank_1
------+-------+--------
a mandarin orange | 100 | 1
watermelon | 80 | 2
Apple | 50 | 3
grapes | 50 | 3
Banana | 50 | 3
lemon | 30 | 6
(6 rows)
test=>
边栏推荐
- The sixth day of the third question of daily Luogu
- [SQL] 自连接的用法
- 微信公众号互助、开白群,小白报团取暖
- Usage of fuser and lsof
- 朋友刚学完自动化测试就拿25Koffer,我功能测试何时才能到头?
- AMD64(x86_64)架构abi文档:
- [steering wheel] tool improvement: common shortcut key set of sublime text 4
- Exclusive interview with ringcentral he Bicang: empowering future mixed office with innovative MVP
- Eslint common error reporting set
- Method of manually cloning virtual machine in esxi6.7
猜你喜欢

MySQL教程:MySQL数据库学习宝典(从入门到精通)

Binary search 33. search rotation sort array

【C语言】深入理解 整型提升 和 算术转换

软件测试岗:阿里三面,幸好做足了准备,已拿offer

Arthas' dynamic load class (retransform)
![[纯理论] YOLO v4: Optimal Speed and Accuracy of Object Detection](/img/1f/f38c3b38feed9e831ad84b4bbf81c0.png)
[纯理论] YOLO v4: Optimal Speed and Accuracy of Object Detection

The LAAS protocol elephant of defi 2.0 is the key to revitalizing the development of defi track

Study notes of pytorch deep learning practice: convolutional neural network (Advanced)

ES6 advanced - using prototype object inheritance methods

Case: using kept+haproxy to build a Web Cluster
随机推荐
Influence of middle tap change on ZVS oscillation circuit
Games101 review: shading, rendering pipelines
massCode 一款优秀的开源代码片段管理器
Be highly vigilant! Weaponization of smartphone location data on the battlefield
Neo4j 导入csv数据报错:Neo4j load csv error : Couldn‘t load the external resource
FPGA_ Initial use process of vivado software_ Ultra detailed
【方向盘】使用IDEA的60+个快捷键分享给你,权为了提效(Live Template&Postfix Completion篇)
How to design automated test cases?
JS get the time composition array of two time periods
Chapter 3 business function development (delete clues)
Recorded target detection NMS (non maximum suppression)
[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (reconstruction)
一切的源头,代码分支策略的选择
这种动态规划你见过吗——状态机动态规划之股票问题(上)
ES6 advanced - inherit parent class attributes with constructors
Skill list of image processing experts
Vofa+ serial port debugging assistant
基础知识-网络与服务器
GAMES101复习:着色(Shading)、渲染管线
Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation