728x90
728x90
728x90

쿼리문을 최적화하는 것은 다른 문제이지만,

기본 쿼리문을 익히는 것은 단순 반복, 습관화하는 것일 뿐이다.

다만, 각 기능의 핵심 예제들을 한번에 보기 위하여 정리한다.

 

간단한 쿼리문은 의미를 적지 않고 넘어간다.

유의사항을 남기도록 하자.

 

(1) (=)

SELECT population

FROM world
WHERE name = 'France'

 

(2) (in category)

SELECT name, population

FROM world
WHERE name IN ('Brazil', 'Russia', 'India', 'China');

name이 category candidates에 속하는 걸로 table 반환

 

(3) (in range)

SELECT name, area

FROM world
WHERE area BETWEEN 250000 AND 300000

(각 숫자는 inclusive이다, 즉 해당 값도 포함시켜 반환함)

 

(4) (multiple conditions)

SELECT name,length(name)

FROM world

WHERE length(name)=5 and region='Europe'

(조건절에 있는 칼럼이 꼭 select한 column일 필요는 없음)

 

(5) (order by)

SELECT select_list

FROM table_name

ORDER BY column1, column2 DESC

(정렬 default는 ASC이므로 column1은 ASC로 ordering)

(column 1기준으로 ASC하고, column 1 값은 고정하고 column2로 DESC함)

 

(6) (order by, making new column)

SELECT orderNumber, orderlinenumber, quantityOrdered * priceEach

FROM orderdetails

ORDER BY quantityOrdered * priceEach DESC;

(이렇게 기존 column을 곱해가지고 new column을 기준으로 order by 가능하기도하고 select도 가능)

 

(7) (order by, making new column, using alias)

SELECT orderNumber, orderLineNumber, quantityOrdered * priceEach AS subtotal

FROM orderdetails

ORDER BY subtotal DESC;

(이렇게 making new column한 것의 alias를 줘서, order by시에 alias를 쓰는게 가능)

 

(8) (order by, custom order)

SELECT orderNumber, status

FROM orders

ORDER BY FIELD(status, 'In Process', 'On Hold', 'Cancelled', 'Resolved', 'Disputed', 'Shipped');

(FIELD(status, 'In Process', ...) 부분은 index of the status in the list ['In Process', ...]을 반환함)

(따라서 이 쿼리문의 결과는 status field에 In Process인 값부터 'Shipped'까지 정렬되어 반환)

 

(9) (like)

SELECT firstName, lastName

FROM employees

WHERE lastName LIKE '%son'

ORDER BY firstName;

(LIKE condition은 특정 pattern이면 True를 반환)

(wild card인 %는 any string of zero or more characters)

(wild card인 _는 any "single" character)

 

(10) (IS NULL)

SELECT lastName, firstName, reportsTo

FROM employees

WHERE reportsTo IS NULL;

(Database에서 NULL이란 missing or unknown을 가리킴, empty string이나 0을 가리키는게 아니니 주의)

 

(11) (<> 혹은 !=)

SELECT lastname, firstname, jobtitle

FROM employees

WHERE jobtitle <> 'Sales Rep';

 

(12) (> 혹은 <)

SELECT lastname, firstname, officeCode

FROM employees

WHERE officecode > 5;

 

(13) (DISTINCT)

SELECT DISTINCT state

FROM customers;

(state column을 가져오면서 duplicates row는 1개만 가져온다.)

(이 때, NULL이 중복이면 1개의 NULL row만 가져온다.)

 

(14) (IS NOT NULL)

SELECT state, city

FROM customers

WHERE state IS NOT NULL

ORDER BY state, city;

 

(15) (DISTINCT multiple columns)

SELECT DISTINCT state, city

FROM customers

WHERE state IS NOT NULL

ORDER BY state, city;

(이 때는 state, city 둘의 값이 동시에 같은 rows를 duplicate row로 취급하여 1개만 반환함)

 

(16) (GROUP BY)

SELECT state

FROM customers

GROUP BY state;

(이는 SELECT DISTINCT state FROM customers;와 같다. 즉 DISTINCT는 GROUP BY의 special case로 보자.)

(MySQl 8.0미만 버전에서는 GROUP BY가 implicit sorting을 하게 된다. 그 이상 버전에서는 하지 않음)

 

(17) (DISTINCT with an aggregate function)

SELECT COUNT(DISTINCT state)

FROM customers

WHERE country = 'USA';

(aggregate function인 COUNT, SUM, AVG 같은 것을 함께 써서 duplicated rows가 없는 취합이 가능)

 

(18) (DISTINCT with LIMIT)

SELECT DISTINCT state

FROM customers

WHERE state IS NOT NULL

LIMIT 5; 

(MySQL은 LIMIT만큼의 결과를 찾은 즉시 searching을 그만 둔다.)

 

(19) (AND with NULL)

SELECT customername, country, state

FROM customers

WHERE country = 'USA' AND state = 'Victoria';

(NULL AND TRUE는 NULL을 반환, 즉 country가 'USA'이고 state가 null이면 select하지 않음)

(NULL AND FALSE는 FALSE을 반환)

 

(20) (OR AND가 존재할 때 판단 순서, Operator precedence)

SELECT true OR false AND false;

(이는 false AND false를 먼저 계산하여 false, 이후 true OR false계산하여 true, 따라서 1을 반환)

 

(21) (OR AND가 존재할 때 순서를 강제하기)

SELECT (true OR false) AND false:

(이렇게 순서를 괄호로 강제하면 true OR false에서 true, true AND false에서 false, 따라서 0을 반환)

 

(22) (OR AND가 여럿 존재하면 반드시 괄호 쓰기)

SELECT customername, country, creditLimit

FROM customers

WHERE country = 'USA' OR country = 'France' AND creditlimit > 10000;

(이 경우 결과는 (country='FRANCE' AND creditlimit>10000) or (country='USA')를 반환함)

(아마도 이 쿼리를 작성한 사람은 이 결과를 원한게 아닐 것이다.)

((country = 'USA' OR count = 'France') AND creditlimit > 10000; 을 사용했어야 했다.)

 

 

 

 

참고자료:

www.mysqltutorial.org/mysql-where/

 

MySQL WHERE

This tutorial shows you how to use MySQL WHERE clause to filter rows based on specified conditions.

www.mysqltutorial.org

 

728x90
728x90

DBMS의 정의:

a software system that enables users to define, create, maintain and control access to the database.

 

DBMS의 특징:

데이터 무결성(Integrity), 즉 primary key역할을 하는 경우 not null, unique등의 제약조건이 필요

데이터의 독립성, 즉 데이터베이스의 크기가 변경되거나 저장소가 변경되어도 DBMS는 잘 동작 해야한다.

보안, 계정별 접근권한에 따른 접근만 가능

데이터 중복 최소화, 여러계정이 데이터베이스를 공유하여 접근함으로써, 각 계정마다 데이터를 중복해서 가질 필요가 없음

응용 프로그램 제작 및 수정이 쉬워짐, 통일된 파일 형식으로 프로그램 작성|유지보수 등이 일관됨

데이터의 안전성 향상, 백업|복원 기능을 제공 

 

간단한 예로

회원정보.xlsx(column이 회원코드, 회원이름, 회원주소 etc),

구매정보.xlsx(column이 회원코드, 회원주소, 상품코드 etc),

이 때 회원이 회원주소를 수정했다면 일일이 두개 파일 모두 수정해야한다.

엑셀파일이 2개가 아니라 많다면?

 

SQL(Structured Query Language)란 DBMS를 통해 정보의 입출력, 관리 등을 할 때 사용하는 언어

표준화된 언어로 각각의 DBMS는 거의다 호환되지만 약간의 차이가 존재하는 형태

클라이언트에서 질의하고 서버가 처리한 후 클라이언트에게 결과를 주는 형태의 대화식 언어

 

 

RDBMS(Relational DBMS)란

데이터를 row와 column을 이루는 하나의 이상의 테이블(=관계, relation)으로 정리하며 primary key가 각 row를 식별한다. 

각 table을 join하여 사용하는 것이 큰 특징

 

 

참고자료:

www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9791162242780&orderClick=LAG&Kc=

 

이것이 MySQL이다 - 교보문고

2016년 출간 후 데이터베이스 도서 분야 부동의 베스트셀러 1위를 지켜오던 『이것이 MySQL이다』가 MySQL 8.0 버전을 반영하여 개정되었다. 특히 ‘파이썬 기초 및 파이썬과 데이터베이스의 연동’,

www.kyobobook.co.kr

en.wikipedia.org/wiki/Relational_database

 

Relational database - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Digital database whose organization is based on the relational model of data A relational database is a digital database based on the relational model of data, as proposed by E. F. Cod

en.wikipedia.org

 

728x90

+ Recent posts