셀프 조인 설명
셀프 조인의 필요성을 이해하지 못합니다. 누군가 나에게 설명해 주시겠습니까?
간단한 예가 매우 도움이 될 것입니다.
셀프 조인을 두 개의 동일한 테이블로 볼 수 있습니다. 그러나 정규화에서는 테이블의 복사본을 두 개 만들 수 없으므로 셀프 조인이있는 두 개의 테이블이있는 것으로 시뮬레이션합니다.
두 개의 테이블이 있다고 가정합니다.
표 emp1
Id Name Boss_id
1 ABC 3
2 DEF 1
3 XYZ 2
표 emp2
Id Name Boss_id
1 ABC 3
2 DEF 1
3 XYZ 2
이제 각 직원의 이름과 상사의 이름을 얻으려면 :
select c1.Name , c2.Name As Boss
from emp1 c1
inner join emp2 c2 on c1.Boss_id = c2.Id
다음 표가 출력됩니다.
Name Boss
ABC XYZ
DEF ABC
XYZ DEF
자신을 참조하는 테이블이있는 경우 매우 일반적입니다. 예 : 모든 직원이 관리자를 가질 수 있고 모든 직원과 해당 관리자의 이름을 나열하려는 직원 테이블.
SELECT e.name, m.name
FROM employees e LEFT OUTER JOIN employees m
ON e.manager = m.id
자체 조인은 자신과 테이블의 조인입니다.
일반적인 사용 사례는 테이블이 항목 (레코드)간에 계층 적 관계가있는 항목을 저장하는 경우입니다 . 예를 들어 개인 정보 (이름, 생년월일, 주소 ...)를 포함하고 아버지 (및 / 또는 어머니)의 ID가 포함 된 열을 포함하는 테이블이 있습니다. 그런 다음 다음과 같은 작은 쿼리로
SELECT Child.ID, Child.Name, Child.PhoneNumber, Father.Name, Father.PhoneNumber
FROM myTableOfPersons As Child
LEFT OUTER JOIN myTableOfPersons As Father ON Child.FatherId = Father.ID
WHERE Child.City = 'Chicago' -- Or some other condition or none
동일한 쿼리에서 자녀와 아버지 (및 어머니, 두 번째 셀프 조인 등, 심지어 조부모 등 ...)에 대한 정보를 얻을 수 있습니다.
다음 users
과 같이 설정된 테이블이 있다고 가정 해 보겠습니다 .
- 사용자 ID
- 사용자 이름
- 사용자의 관리자 ID
이 상황 에서 한 쿼리에서 사용자 정보 와 관리자 정보를 모두 가져 오려면 다음을 수행 할 수 있습니다.
SELECT users.user_id, users.user_name, managers.user_id AS manager_id, managers.user_name AS manager_name INNER JOIN users AS manager ON users.manager_id=manager.user_id
테이블이 자기 참조 인 경우 유용합니다. 예를 들어 페이지 테이블의 경우 각 페이지에 next
및 previous
링크 가있을 수 있습니다 . 이는 동일한 테이블에있는 다른 페이지의 ID입니다. 어떤 시점에서 연속 된 페이지의 세 개를 얻으려면 동일한 테이블의 열 을 사용하여 next
및 previous
열에 대해 두 개의 자체 조인을 수행합니다 id
.
Employee
아래에 설명 된 테이블이 있다고 상상해보십시오 . 모든 직원에게는 직원이기도 한 관리자가 있습니다 (Manager_id가 null 인 CEO 제외)
Table (Employee):
int id,
varchar name,
int manager_id
그런 다음 다음 선택을 사용하여 모든 직원과 관리자를 찾을 수 있습니다.
select e1.name, e2.name as ManagerName
from Employee e1, Employee e2 where
where e1.manager_id = e2.id
Without the ability for a table to reference itself, we'd have to create as many tables for hierarchy levels as the number of layers in the hierarchy. But since that functionality is available, you join the table to itself and sql treats it as two separate tables, so everything is stored nicely in one place.
Apart from the answers mentioned above (which are very well explained), I would like to add one example so that the use of Self Join can be easily shown. Suppose you have a table named CUSTOMERS which has the following attributes: CustomerID, CustomerName, ContactName, City, Country. Now you want to list all those who are from the "same city" . You will have to think of a replica of this table so that we can join them on the basis of CITY. The query below will clearly show what it means:
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2,
A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
There are many correct answers here, but there is a variation that is equally correct. You can place your join conditions in the join statement instead of the WHERE clause.
SELECT e1.emp_id AS 'Emp_ID'
, e1.emp_name AS 'Emp_Name'
, e2.emp_id AS 'Manager_ID'
, e2.emp_name AS 'Manager_Name'
FROM Employee e1 RIGHT JOIN Employee e2 ON e1.emp_id = e2.emp_id
Keep in mind sometimes you want e1.manager_id > e2.id
The advantage to knowing both scenarios is sometimes you have a ton of WHERE or JOIN conditions and you want to place your self join conditions in the other clause to keep your code readable.
No one addressed what happens when an Employee does not have a manager. Huh? They are not included in the result set. What if you want to include employees that do not have managers but you don't want incorrect combinations returned?
Try this puppy;
SELECT e1.emp_id AS 'Emp_ID'
, e1.emp_name AS 'Emp_Name'
, e2.emp_id AS 'Manager_ID'
, e2.emp_name AS 'Manager_Name'
FROM Employee e1 LEFT JOIN Employee e2
ON e1.emp_id = e2.emp_id
AND e1.emp_name = e2.emp_name
AND e1.every_other_matching_column = e2.every_other_matching_column
One use case is checking for duplicate records in a database.
SELECT A.Id FROM My_Bookings A, My_Bookings B
WHERE A.Name = B.Name
AND A.Date = B.Date
AND A.Id != B.Id
Self-join is useful when you have to evaluate the data of the table with itself. Which means it'll correlate the rows from the same table.
Syntax: SELECT * FROM TABLE t1, TABLE t2 WHERE t1.columnName = t2.columnName
For example, we want to find the names of the employees whose Initial Designation equals to current designation. We can solve this using self join in following way.
SELECT NAME FROM Employee e1, Employee e2 WHERE e1.intialDesignationId = e2.currentDesignationId
It's the database equivalent of a linked list/tree, where a row contains a reference in some capacity to another row.
Here is the exaplanation of self join in layman terms. Self join is not a different type of join. If you have understood other types of joins (Inner, Outer, and Cross Joins), then self join should be straight forward. In INNER, OUTER and CROSS JOINS, you join 2 or more different tables. However, in self join you join the same table with itslef. Here, we don't have 2 different tables, but treat the same table as a different table using table aliases. If this is still not clear, I would recomend to watch the following youtube videos.
참고URL : https://stackoverflow.com/questions/2458519/explanation-of-self-joins
'Nice programing' 카테고리의 다른 글
CORBA는 레거시입니까? (0) | 2020.10.16 |
---|---|
Eclipse-분할보기의 동일한 .Java 파일? (0) | 2020.10.16 |
페이지에 src 대신 iframe의 콘텐츠 지정 (0) | 2020.10.16 |
응답 본문이 HTTP-DELETE- 요청에 허용됩니까? (0) | 2020.10.16 |
실패한 JUnit 테스트를 즉시 다시 실행하는 방법은 무엇입니까? (0) | 2020.10.16 |