저장을 습관화
SQL - UNION 본문
1. union
두 개 이상의 select 문의 결과를 결합한다.
단, 이를 위한 조건이 있다.
- union 내 모든 select 문에는 동일한 수의 열이 존재할 것
- 열의 데이터 유형이 유사할 것
- 모든 selecct 문의 열이 동일한 순서로 되어 있을 것
union 연산자는 기본적으로 중복을 제거한 고유한 값만 출력한다.
중복값을 허용하려면 union all을 사용한다.
union 연산자를 사용하여 출력된 결과 집합의 열 이름은
첫번째 select 문에서 사용한 열 이름이 된다.
예시 테이블 1. Customers
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 5021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 5023 | Mexico |
예시 테이블 2. Suppliers
SupplierID | SupplierName | ContactName | Address | City | PostalCode | Country |
1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | London | EC1 4SD | UK |
2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA |
3 | Grandma Kelly's Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA |
예시 1)
select city from customers
union
select city from suppliers
order by city
이하 생략..
예시 2) union all
select city from customers
union all
select city from suppliers
order by city
중복된 값의 생략을 하지 않아 120개의 레코드가 출력되었다.
이하 생략..
예시 3) SQL UNION With WHERE
select city from customers
where country = "Germany"
union
select city from suppliers
where country = "Germany"
order by city
이하 생략..
예시 4) 모든 고객과 공급자를 나열하는 쿼리문
select 'Customer' as Type, contactname, city, country
from customers
union
select 'Supplier', contactname, city, country
from suppliers
'Type' alias를 사용하여 임시적인 열에 이름을 지정하였다.
이 별칭은 위 쿼리의 결과에서만 존재하며,
customers 테이블에서 가져온 데이터라면 Type 열에 'Customer',
suppliers 테이블에서 가져온 데이터라면 Type 열에 'Supplier' 라고 표시된다.
중략..
'공부 > 데이터베이스' 카테고리의 다른 글
SQL - ANY, ALL (0) | 2023.12.07 |
---|---|
SQL - GROUP BY, HAVING, EXISTS (0) | 2023.12.04 |
SQL - ORDER BY, IN, BETWEEN, Aliases (0) | 2023.12.03 |
SQL - AND, OR, NOT (0) | 2023.12.03 |
SQL - SELECT, DISTINCT, WHERE (0) | 2023.12.03 |