Qu'est-ce qu'une auto-jointure en SQL ?
Une auto-jointure en SQL est un type de jointure dans lequel une table est jointe à elle-même. Ceci est utile lorsque vous souhaitez comparer des lignes dans la même table ou récupérer des données associées à partir du même ensemble de données. Les auto-jointures sont souvent utilisées pour modéliser des relations hiérarchiques (comme les structures employé-manager) ou pour trouver des combinaisons au sein d'un ensemble (comme des confrontations possibles entre équipes).
Définition :
Une auto-jointure est une jointure régulière où la table est jointe à elle-même en utilisant différents alias. Il est essentiellement utilisé pour comparer les lignes d'un tableau à d'autres lignes du même tableau.
Syntaxe :
SELECT a.column1, b.column2 FROM table_name a JOIN table_name b ON a.common_column = b.common_column;
Explication :
- table_name a : crée un alias (a) pour la table.
- table_name b : crée un autre alias (b) pour la même table.
- ON a.common_column = b.common_column : La condition pour joindre les deux alias en fonction des colonnes communes.
1. Exemple d'auto-adhésion : scénario d'employé et de gestionnaire
Scénario :
Vous disposez d'une table Employés et vous devez savoir quel employé relève de quel responsable. Chaque ligne du tableau contient les détails des employés et la colonne ManagerID contient l'EmployeeID du manager.
Création d'un exemple de tableau et insertion de données :
-- Create the Employees table CREATE TABLE Employees ( EmployeeID NUMBER PRIMARY KEY, EmployeeName VARCHAR2(50), ManagerID NUMBER );
-- Insert sample data INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES (1, 'John', NULL); INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES (2, 'Mike', 1); INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES (3, 'Sarah', 1); INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES (4, 'Kate', 2); INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES (5, 'Tom', 2); -- Commit the changes COMMIT;
Requête d'auto-jointure dans Oracle :
SELECT e1.EmployeeName AS Employee, e2.EmployeeName AS Manager FROM Employees e1 LEFT JOIN Employees e2 ON e1.ManagerID = e2.EmployeeID;
Explication :
- e1 est un alias représentant les employés.
- e2 est un autre alias représentant les managers.
LEFT JOIN permet d'inclure tous les employés, même ceux qui n'ont pas de manager (ManagerID est NULL).
Sortie :
Employee | Manager |
---|---|
John | NULL |
Mike | John |
Sarah | John |
Kate | Mike |
Tom | Mike |
2. Exemple d'auto-adhésion : matchs IPL (chaque équipe joue une fois contre chaque autre équipe)
Scénario :
Vous avez une liste d'équipes IPL et vous souhaitez générer une liste de matchs où chaque équipe joue une fois contre toutes les autres équipes.
Création d'un exemple de tableau et insertion de données :
-- Create the Teams table CREATE TABLE Teams ( TeamID NUMBER PRIMARY KEY, TeamName VARCHAR2(100) );
-- Insert sample data INSERT INTO Teams (TeamID, TeamName) VALUES (1, 'Mumbai Indians'); INSERT INTO Teams (TeamID, TeamName) VALUES (2, 'Chennai Super Kings'); INSERT INTO Teams (TeamID, TeamName) VALUES (3, 'Royal Challengers Bangalore'); INSERT INTO Teams (TeamID, TeamName) VALUES (4, 'Kolkata Knight Riders'); -- Commit the changes COMMIT;
Requête d'auto-jointure dans Oracle :
SELECT t1.TeamName AS Team1, t2.TeamName AS Team2 FROM Teams t1 JOIN Teams t2 ON t1.TeamID <p><strong>Explication :</strong></p>
- t1 et t244 sont des alias pour la table Teams.
La condition t1.TeamID
Sortie :
Team1 | Team2 |
---|---|
Mumbai Indians | Chennai Super Kings |
Mumbai Indians | Royal Challengers Bangalore |
Mumbai Indians | Kolkata Knight Riders |
Chennai Super Kings | Royal Challengers Bangalore |
Chennai Super Kings | Kolkata Knight Riders |
Royal Challengers Bangalore | Kolkata Knight Riders |
3. Self-Join Example: IPL Matches (Every Team Plays Against Every Other Team Twice)
Scenario:
You want to generate a list where each IPL team plays against every other team twice (once as the home team, and once as the away team).
Self-Join Query in Oracle:
SELECT t1.TeamName AS Team1, t2.TeamName AS Team2 FROM Teams t1 JOIN Teams t2 ON t1.TeamID != t2.TeamID;
Explanation:
- t1 and t2 are aliases for the Teams table.
The condition t1.TeamID != t2.TeamID ensures that all possible match-ups are listed, including both Team A vs. Team B and Team B vs. Team A.
Output:
Team1 | Team2 |
---|---|
Mumbai Indians | Chennai Super Kings |
Mumbai Indians | Royal Challengers Bangalore |
Mumbai Indians | Kolkata Knight Riders |
Chennai Super Kings | Mumbai Indians |
Chennai Super Kings | Royal Challengers Bangalore |
Chennai Super Kings | Kolkata Knight Riders |
Royal Challengers Bangalore | Mumbai Indians |
Royal Challengers Bangalore | Chennai Super Kings |
Royal Challengers Bangalore | Kolkata Knight Riders |
Kolkata Knight Riders | Mumbai Indians |
Kolkata Knight Riders | Chennai Super Kings |
Kolkata Knight Riders | Royal Challengers Bangalore |
Finding Duplicate Customer Records - Additional Example
Scenario:
You have a Customers table where each customer should have a unique combination of FirstName, LastName, and DateOfBirth. However, there may be accidental duplicates, and you want to identify them using a self-join.
Sample Table Creation and Data Insertion:
-- Create the Customers table CREATE TABLE Customers ( CustomerID NUMBER PRIMARY KEY, FirstName VARCHAR2(50), LastName VARCHAR2(50), DateOfBirth DATE );
-- Insert sample data (including duplicates) INSERT INTO Customers (CustomerID, FirstName, LastName, DateOfBirth) VALUES (1, 'John', 'Doe', TO_DATE('1990-01-01', 'YYYY-MM-DD')); INSERT INTO Customers (CustomerID, FirstName, LastName, DateOfBirth) VALUES (2, 'Jane', 'Smith', TO_DATE('1992-02-02', 'YYYY-MM-DD')); INSERT INTO Customers (CustomerID, FirstName, LastName, DateOfBirth) VALUES (3, 'John', 'Doe', TO_DATE('1990-01-01', 'YYYY-MM-DD')); INSERT INTO Customers (CustomerID, FirstName, LastName, DateOfBirth) VALUES (4, 'Alice', 'Johnson', TO_DATE('1995-03-03', 'YYYY-MM-DD')); INSERT INTO Customers (CustomerID, FirstName, LastName, DateOfBirth) VALUES (5, 'John', 'Doe', TO_DATE('1990-01-01', 'YYYY-MM-DD')); -- Commit the changes COMMIT;
Self-Join Query to Find Duplicates:
SELECT c1.CustomerID AS DuplicateRecordID1, c2.CustomerID AS DuplicateRecordID2, c1.FirstName, c1.LastName, c1.DateOfBirth FROM Customers c1 JOIN Customers c2 ON c1.FirstName = c2.FirstName AND c1.LastName = c2.LastName AND c1.DateOfBirth = c2.DateOfBirth AND c1.CustomerID <p><strong>Explanation:</strong></p>
- c1 and c2 are aliases for the same Customers table.
- The condition c1.FirstName = c2.FirstName AND c1.LastName = c2.LastName AND c1.DateOfBirth = c2.DateOfBirth checks for matching values across multiple columns, indicating a duplicate.
- c1.CustomerID
Output:
RecordID1 | RecordID2 | FirstName | LastName | DateOfBirth |
---|---|---|---|---|
1 | 3 | John | Doe | 1990-01-01 |
1 | 5 | John | Doe | 1990-01-01 |
3 | 5 | John | Doe | 1990-01-01 |
Conclusion:
- A self-join allows you to connect rows from the same table by creating multiple aliases. It is useful in scenarios where data needs to be compared within the same dataset. In the above examples:
- The employee-manager example shows how to use self-joins for hierarchical data.
- The IPL match-ups illustrate how to generate combinations within a single dataset, whether for a single match per pair or double matches (home and away games).
- These scenarios demonstrate the flexibility and power of self-joins in SQL.
以上是SQL 中的自连接 |最好的例子解释的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

将矩阵电影特效带入你的网页!这是一个基于著名电影《黑客帝国》的酷炫jQuery插件。该插件模拟了电影中经典的绿色字符特效,只需选择一张图片,插件就会将其转换为充满数字字符的矩阵风格画面。快来试试吧,非常有趣! 工作原理 插件将图片加载到画布上,读取像素和颜色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地读取图片的矩形区域,并利用jQuery计算每个区域的平均颜色。然后,使用

本文将引导您使用jQuery库创建一个简单的图片轮播。我们将使用bxSlider库,它基于jQuery构建,并提供许多配置选项来设置轮播。 如今,图片轮播已成为网站必备功能——一图胜千言! 决定使用图片轮播后,下一个问题是如何创建它。首先,您需要收集高质量、高分辨率的图片。 接下来,您需要使用HTML和一些JavaScript代码来创建图片轮播。网络上有很多库可以帮助您以不同的方式创建轮播。我们将使用开源的bxSlider库。 bxSlider库支持响应式设计,因此使用此库构建的轮播可以适应任何

核心要点 利用 JavaScript 增强结构化标记可以显着提升网页内容的可访问性和可维护性,同时减小文件大小。 JavaScript 可有效地用于为 HTML 元素动态添加功能,例如使用 cite 属性自动在块引用中插入引用链接。 将 JavaScript 与结构化标记集成,可以创建动态用户界面,例如无需页面刷新的选项卡面板。 确保 JavaScript 增强功能不会妨碍网页的基本功能至关重要;即使禁用 JavaScript,页面也应保持功能正常。 可以使用高级 JavaScript 技术(

数据集对于构建API模型和各种业务流程至关重要。这就是为什么导入和导出CSV是经常需要的功能。在本教程中,您将学习如何在Angular中下载和导入CSV文件


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。