[MySqL] Select문

2024. 7. 21. 22:19WebBack/MySQL

Select문이란?

셀렉트문은 테이블에서 하나 혹은 그 이상의 레코드(records, 연관된 필드의 집합 즉 행row)를 검색할 때 사용한다. 

 

기본 문법

SELECT expressions
FROM tables
[WHERE conditions];

표현식(expressions): 검색하고 싶은 열(columns) 혹은 계산(Calculations)을 말한다. 전체를 검색하고 싶으면 *를 넣으면 된다. 

테이블(tables): 레코드를 얻고자 하는 테이블을 말한다. From 절에는 무조건 하나 이상이 들어가야 한다. 

WHERE 조건(condition): 선택적. 레코드가 충족해야할 조건을 말한다. 

전체 문법

 

예시

1. 한 테이블의 모든 필드를 선택할 때

SELECT *
FROM order_details
WHERE quantity >= 10
ORDER BY quantity DESC;

 

위 코드는 이러한 의미이다. 

1. 'order_details' 테이블 중에 모두 수량(quantity)은 10과 같거나 많은

2. 모든 필드를 선택하기를 원한다. 

3. 결과 집합은 수량에 따라 내림차순(descending order)으로 정렬된다. 

 

2. 한 테이블의 개별 필드를 선택할 때

SELECT order_id, quantity, unit_price
FROM order_details
WHERE quantity < 500
ORDER BY quantity ASC, unit_price DESC;

 

위 코드는 이러한 의미이다. 

1. 'order_details' 테이블에서 수량은 500보다 작은 

2. 'order_id', 'quantity', 'unit_price' 필드를 선택하기를 원한다. 

3. 결과 집합은 수량에 따라 오름차순(ascending order)으로 정렬되고, 그 다음에 가격(unit_price)에 따라 내림차순으로 정렬된다. 

3. 여러 테이블에서 필드를 선택할 때

SELECT order_details.order_id, customers.customer_name
FROM customers
INNER JOIN order_details
ON customers.customer_id = order_details.customer_id
ORDER BY order_id;

위 코드는 이러한 의미이다. 

1. 'customers' 테이블 'order_details' 테이블에서 'customer_id'값이 서로 매치되는 

2. 'order_id'와 'customer_name' 필드를 선택하기를 원한다. 

3. 결과 집합은 'order_id'에 따라 오름차순(생략됨)으로 정렬된다. 

4. 파일로 작성한다

SELECT order_id, quantity, unit_price
FROM order_details
WHERE quantity < 500
ORDER BY quantity
INTO OUTFILE 'results.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n';

위 코드는 이러한 의미이다. 

1. 'order_details' 테이블에서 수량이 500보다 작은 

2.  'order_id', 'quantity', 'unit_price' 필드 선택하여 반환하기를 원한다. 

3. 결과 집합은 수량에 따라 오름차순(생략됨)으로 정렬된다. 

4. 그리고 이름이 'results.txt'인 파일을 만든다. 

 

https://www.techonthenet.com/mysql/select.php

 

MySQL: SELECT Statement

MySQL: SELECT Statement This MySQL tutorial explains how to use the MySQL SELECT statement with syntax and examples. Description The MySQL SELECT statement is used to retrieve records from one or more tables in MySQL. Syntax In its simplest form, the synta

www.techonthenet.com