24.SQL INNER JOIN
24.SQL INNER JOIN
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 |
CategoryID 두 테이블의 필드를 사용하여 Products테이블과 Categories 테이블을 조인합니다.
예
INNER JOIN 키워드로 제품과 카테고리를 결합하세요
SELECT ProductID , ProductName , CategoryName
FROM Products
INNER JOIN Categories ON Products.CatogoryID = Categories.CategoryID;
참고 : INNER JOIN 키워드는 두 테이블 모두에서 일치하는 행만을 반환합니다.
즉 CategoryID가 없는 제품이나 Categories 테이블에 없는 CategoryID 가 있는 경우 해당 레코드는 결과를 반환되지 않습니다.
-열 이름 지정
SQL 문에서 열을 지정할 때 테이블 이름을 포함하는 것이 좋습니다.
예
테이블 이름을 지정하세요
SELECT Products.ProductsID , Products.ProductsName , Categories.CategoryName
FROM Products
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID;
CategoryID 위에 예는 테이블 이름을 지정하지 않고도 작동합니다.
지정된 열 이름이 두 테이블에 모두 없기 때문입니다.
명령문에 포함하려고 하면 SELECT 테이블 이름을 지정하지 않으면 오류가 발생하빈다
(CategoryID 두 테이블에 모두 있기 떄문입니다)
-JOIN 또는 INNER JOIN
JOIN , INNER JOIN 동일한 결과가 반환됩니다.
INNER 는 조인의 기본 유형으로 INNER JOIN 에서 INNER 가 생략될 수 있습니다.
-3개의 테이블 조인
다음 SQL 문은 고객 및 운송업체 정보가 있는 모든 주문을 선택합니다
다음은 Shippers의 테이블입니다.
ShipperID ShipperName Phone
1 | Speedy Express | (503) 555-9831 |
2 | United Package | (503) 555-3199 |
3 | Federal Shipping | (503) 555-9931 |
예
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);