저장을 습관화
SQL - INNER JOIN 본문
1. INNER JOIN
두 테이블 모두에서 일치하는 값이 있는 레코드를 선택한다.
예시 테이블 Products)
ProductID | ProductName | CategoryID | Price |
1 | Chais | 1 | 18 |
2 | Chang | 1 | 19 |
3 | Aniseed Syrup | 2 | 10 |
예시 테이블 Categories)
CategoryID | CategoryName | Description |
1 | Beverages | Soft drinks, coffees, teas, beers, and ales |
2 | Condiments | Sweet and savory sauces, relishes, spreads, and seasonings |
3 | Confections | Desserts, candies, and sweet breads |
예시 1)
select ProductID, ProductName, CategoryName
from Products
inner join Categories on Products.CategoryID = Categories.CategoryID
이하 생략..
INNER JOIN 키워드는 두 테이블 모두에서 일치하는 행만 반환한다.
즉, CategoryID가 없거나 CategoryID가 Categories 테이블에 없는 제품이 있다면
해당 레코드는 결과에 포함되지 않는다.
예시 2) select할 컬럼이 어느 테이블에 속한 것인지 명시적으로 작성
select Products.ProductID, Products.ProductName, Categories.CategoryName
from Products
inner join Categories on Products.CategoryID = Categories.CategoryID
예시 1에서는 ProductID, ProductName, CategoryName과 같이 하나의 테이블에서만 존재하는 컬럼명이었기에
에러 없이 동작했지만
만약 ProductID와 같이 두 테이블에 공통적으로 존재하는 컬럼명만을 적었다면
어느 테이블에서 내용을 가져와야하는지에 대한 에러가 발생한다.
예시 3) INNER JOIN은 JOIN의 기본 조인 유형이다.
inner라는 키워드 없이 join만 적더라도 이는 자동으로 inner join으로써 동작한다.
select Products.ProductID, Products.ProductName, Categories.CategoryName
from Products
join Categories on Products.CategoryID = Categories.CategoryID
예시 4) 3개의 테이블을 INNER JOIN, (괄호)로 묶는다.
select Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
from ((Orders
inner join Customers on Orders.CustomerID = Customers.CustomerID)
inner join Shippers on Orders.ShipperID = Shippers.ShipperID)
이하 생략..
'공부 > 데이터베이스' 카테고리의 다른 글
SQL - FULL JOIN, SELF JOIN (0) | 2023.12.09 |
---|---|
SQL - LEFT JOIN, RIGHT JOIN (0) | 2023.12.09 |
SQL - JOINS (0) | 2023.12.08 |
SQL - ANY, ALL (0) | 2023.12.07 |
SQL - GROUP BY, HAVING, EXISTS (0) | 2023.12.04 |