MYSQL

연결 연산자(||), 정렬 (ORDER BY), 중복 제거(DISTINCT)

soo15 2023. 5. 5. 16:48

 

1. 연결 연산자 사용하기 (||)

연결 연산자(concatenation operator)은 컬럼과 컬럼을 서로 연결하여 출력한다.

 

 

Customers table

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Avda. de la Constitución 2222 México D.F 05021 Mexico
3 Antonio Moreno Mataderos 2312 México D.F 05023 Mexico
:
:
:
:
:
:
:
:
:
:
:
:
:
:

 

> 연결 연산자 사용하고 싶을 때  ||를 이용하여 다음과 같이 작성한다.

SELECT CustomerName || '의 ID는 ' || customerID || '입니다.' as '고객 아이디'
  FROM Customers;

 

출력결과

고객 아이디
Alfreds Futterkiste의 ID는 1입니다.
Ana Trujillo Emparedados y helados의 ID는 2입니다.
Antonio Moreno Taquería의 ID는 3입니다.
Around the Horn의 ID는 4입니다.
:
:

 

 

 

 

 

2. 데이터 정렬하기 (ORDER BY)

ORDER BY절은 작성 시 맨 마지막에 작성한다.
ORDER BY절에 컬럼명 대신 숫자를 적어줄 수도 있다.

 

* 오름차순 정렬 : ORDER BY  컬럼명  (ASC 생략 가능)
* 내림차순 정렬ORDER BY  컬럼명 DESC

 

 

Orderdetails table

OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
:
:
:
:
:
:
:
:

 

> OrderDetailID, OrderID, ProductID를 출력하고
   OrderID를 오름차순으로 정렬 후 ProductID는 내림차순으로 정렬하고 싶을 때 다음과 같이 작성한다.

   (ASC는 생략가능)

  SELECT OrderDetailID, OrderID, ProductID
  FROM orderdetails
  ORDER BY OrderID ASC, ProductID DESC

 

> 위의 쿼리에서 컬럼명 대신 숫자를 적을 수 있다. 

  (ASC는 생략가능,  SELECT절에 적혀있는

   OrderDetailID, OrderID, ProductID는 순서대로 1, 2, 3 에 해당)

SELECT OrderDetailID, OrderID, ProductID
  FROM orderdetails
  ORDER BY 2 ASC, 3 DESC

 

 

출력결과

(OrderID를 오름차순으로 정렬 후 ProductID는 내림차순)

OrderDetailID
OrderID  ProductID
3 10248  72
2 10248  42
1 10248  11
5 10249  51
4 10249  14
:
:
:
:
:
:

 

 

 

 

 

3. 중복 데이터 제거하기 (DISTINCT)

중복된 데이터를 제거하고 출력할 때
SELECT절에 DISTINCT를 작성한 후 컬럼명을 작성한다.

 

Customers table

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Avda. de la Constitución 2222 México D.F 05021 Mexico
3 Antonio Moreno Mataderos 2312 México D.F 05023 Mexico
:
:
:
:
:
:
:
:
:
:
:
:
:
:

 

> 중복 데이터 제거하고 country를 출력하면 다음과 같다.

SELECT DISTINCT country
  FROM Customers
  ORDER BY country
  LIMIT 3

 

출력결과

Country
Argentina
Austria
Belgium

 

 

 

 비교) DISTINCT 없을 때

SELECT country
  FROM Customers
  ORDER BY country
  LIMIT 3

 

출력결과

Country
Argentina
Argentina
Argentina