๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
6๏ธโƒฃ SQL/SQL ์ •๋ฆฌ

[MySQL] ์ฝ”๋”ฉํ…Œ์ŠคํŠธ๋ฅผ ์œ„ํ•œ SQL ๋ฌธ๋ฒ•

by seolhee2750 2022. 2. 4.
DISTINCT ์ค‘๋ณต ์ œ๊ฑฐ
SELECT DISTINCT NAME

 

LIMIT ๊ฒฐ๊ณผ ๊ฐœ์ˆ˜ ์ œํ•œ (์ƒ์œ„ ๋ช‡ ๊ฐœ๋งŒ ์ถœ๋ ฅ)
# ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜์—ฌ ๊ฐ€์žฅ ์ž‘์€ ๊ฒƒ๋ถ€ํ„ฐ 3๊ฐœ ์ถœ๋ ฅ
ORDER BY ID
LIMIT 3

 

IN ๋’ค์— ์˜ค๋Š” ๋ฐ์ดํ„ฐ์— ํฌํ•จ๋˜๋Š”์ง€ ํŒ๋‹จ
# IN
WHERE ID IN (SELECT ID FROM ...)

# NOT IN
WHERE ID NOT IN (SELECT ID FROM ...)

 

IS NULL null์ธ์ง€ ํŒ๋‹จ
# IS NULL
WHERE A.ID IS NULL

# IS NOT NULL
WHERE A.ID IS NOT NULL

 

LIKE ๋’ค์— ์˜ค๋Š” ๋ฌธ์ž์—ด์— ํฌํ•จ๋˜๋Š”์ง€ ํŒ๋‹จ
# ๋์ด AB๋กœ ๋๋‚˜๋Š” NAME ์ฐพ๊ธฐ
WHERE NAME LIKE '%AB'

# AB๋กœ ์‹œ์ž‘ํ•˜๋Š” NAME ์ฐพ๊ธฐ
WHERE NAME LIKE 'AB%'

# AB๊ฐ€ ๋“ค์–ด๊ฐ€๋Š” NAME ์ฐพ๊ธฐ
WHERE NAME LIKE '%AB%'

 

COUNT ๊ฐœ์ˆ˜ ์„ธ๊ธฐ
SELECT COUNT(ID)

 

ABS ์ ˆ๋Œ“๊ฐ’
SELECT ABS(-10)

 

HOUR ์‹œ๊ฐ„๋งŒ ์ถœ๋ ฅ
# YEAR, HOUR, MONTH, DAY ๋“ฑ ๋…„๋„๋ถ€ํ„ฐ ์ดˆ๊นŒ์ง€ ์žˆ์Œ
SELECT HOUR(DATETIME)

 

DATE_FORMAT ์‹œ๊ฐ„ ํ‘œํ˜„ ์กฐ์ • (์ฐธ๊ณ  : https://devjhs.tistory.com/89)
SELECT DATE_FORMAT(DATETIME, '%Y-%m-%d')

# ๋’ค์— ์ ๋Š” ๋ฌธ์ž์—ด์˜ ํ‘œํ˜„์„ ๋‹ค์–‘ํ•˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ์Œ
# '%Y-%m-%d' -> 2022, 02, 03
# '%y, %m, %d' -> 22, 02, 03
# '%y๋…„ %m์›” %d์ผ' -> 22๋…„ 02์›” 03์ผ

 

POW ์ œ๊ณฑ
# 10์˜ 2์ œ๊ณฑ
SELECT POW(10, 2)

 

ROUND, TURNCATE ๋ฐ˜์˜ฌ๋ฆผ, ๋ฒ„๋ฆผ
# ์ž๋ฆฟ์ˆ˜ ๊ธฐ์ค€ ๋ฐ˜์˜ฌ๋ฆผ
SELECT ROUND(1.234) # 1
SELECT ROUND(1.234, 1) # 1.2
SELECT ROUND(10.2) # 10

# ์ž๋ฆฟ์ˆ˜ ๊ธฐ์ค€ ๋ฒ„๋ฆผ
SELECT TRUNCATE(1.234) # 1
SELECT TRUNCATE(1.234, 1) # 1.2
SELECT TRUNCATE(10.2) # 10

 

CASE ์กฐ๊ฑด๋ฌธ
# CASE WHEN THEN ELSE END ํ˜•์‹์œผ๋กœ ์‚ฌ์šฉ
SELECT 
CASE
WHEN SEX_UPON_INTAKE LIKE "apple%"
THEN "O"
ELSE "X"
END
AS "APPLE"

 

IF ์กฐ๊ฑด๋ฌธ
# IF(์กฐ๊ฑด, True๊ฒฐ๊ณผ, False๊ฒฐ๊ณผ) ํ˜•์‹์œผ๋กœ ์‚ฌ์šฉ
SELECT IF(NAME LIKE '%apple', 'O', 'X') AS APPLE

 

= ๋น„๊ต ์—ฐ์‚ฐ์ž
# !=, >=, < ๋“ฑ์ด ์žˆ์ง€๋งŒ, =์˜ ๊ฒฝ์šฐ ==๊ฐ€ ์•„๋‹ˆ๋ผ =๋กœ ์‚ฌ์šฉํ•œ๋‹ค๋Š” ์ 
WHERE NAME = 'Dog'

 

SET ๋ณ€์ˆ˜ ์„ ์–ธ
# @๋ฅผ ๋ถ™์—ฌ์„œ ํ”„๋กœ์‹œ์ €๊ฐ€ ์ข…๋ฃŒ๋˜์–ด๋„ ์œ ์ง€๋˜๋„๋ก ์„ค์ •
# :=๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ’ ๋Œ€์ž…
SET @num := -1;

SELECT (@num := @num + 1) AS NUM, (
SELECT COUNT(*) FROM TABLE_A WHERE @num = ID) AS COUNT
FROM TABLE_A
WHERE @num < 10

'6๏ธโƒฃ SQL > SQL ์ •๋ฆฌ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[SQL] DDL, DML, DCL, TCL ์š”์•ฝ  (0) 2022.09.15
[MySQL] INNER, OUTER JOIN ์ •๋ฆฌ  (0) 2022.02.03

๋Œ“๊ธ€