DB(Database)/MySQL

[MySQL] MySQL ๋ณ€์ˆ˜ ์‚ฌ์šฉ๋ฐฉ๋ฒ•(SET, PREPARE, EXECUTE)๊ณผ ๋ฐ์ดํ„ฐ ํ˜•์‹ ๋ณ€ํ™˜ ํ•จ์ˆ˜(CAST, CONVERT,CONCAT), ๋‚ด์žฅํ•จ์ˆ˜(์ œ์–ดํ•จ์ˆ˜ IF, IFNULL, NULLIF, CASE WHEN ELSE END)

ํƒฑ์ ค 2021. 1. 20. 00:12

๋ณ€์ˆ˜ ์‚ฌ์šฉ ํ˜•์‹

SET @๋ณ€์ˆ˜๋ช… = ๋ณ€์ˆ˜๊ฐ’; -- ๋ณ€์ˆ˜ ์„ ์–ธ, ๊ฐ’ ๋Œ€์ž…
SELECT @๋ณ€์ˆ˜์ด๋ฆ„; -- ๋ณ€์ˆ˜ ์ถœ๋ ฅ

์˜ˆ์ œ

SET @VAR1 = 1;
SET @VAR2 = 2;

SELECT @VAR1; -- ๊ฒฐ๊ณผ 1
SELECT @VAR1 + @VAR2; -- ๊ฒฐ๊ณผ 2

๊ฒฐ๊ณผ 1, ๊ฒฐ๊ณผ2

SET, PREPARE, EXECUTE ๋ฌธ

SET @VAR1 = 1;
PREPARE Query
	FROM 'SELECT * FROM [ํ…Œ์ด๋ธ”๋ช…] ORDER BY [์ •๋ ฌ๊ธฐ์ค€] LIMIT ?'; 	-- '?'์œ„์น˜์— ๋ณ€์ˆ˜ ์‚ฌ์šฉํ•ด ์ฟผ๋ฆฌ๋ฌธ PREPARE
EXECUTE Query USING @VAR1; -- ๋ณ€์ˆ˜ ์‹คํ–‰๋ฌธ

๋ฐ์ดํ„ฐ ํ˜•์‹ ๋ณ€ํ™˜ ํ•จ์ˆ˜

  • CONVERT(), CAST(): ๊ฐ•์ œ๋กœ ๋ฐ์ดํ„ฐํ˜•์„ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜
-- ๋ฐ์ดํ„ฐ๋ฅผ ์ •์ˆ˜๋กœ ์ถœ๋ ฅ
SELECT CAST([๋ฐ์ดํ„ฐ] AS SIGNED INTEGER) AS '๋ถˆ๋Ÿฌ์˜ฌ ์ด๋ฆ„' FROM [ํ…Œ์ด๋ธ”๋ช…];
SELECT CONVERT([๋ฐ์ดํ„ฐ], SIGNED INTEGER) AS '๋ถˆ๋Ÿฌ์˜ฌ ์ด๋ฆ„' FROM [ํ…Œ์ด๋ธ”๋ช…];
  • CAST()์˜ˆ์ œ
    • ๋‹ค์–‘ํ•œ ๊ตฌ๋ถ„์ž($, /, %, @)๋ฅผ ๋‚ ์งœ ํ˜•์‹(-)์œผ๋กœ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅ
SELECT CAST('2021$01$19' AS DATE);
SELECT CAST('2021/01/19' AS DATE);
SELECT CAST('2021%01%19' AS DATE);
SELECT CAST('2021@01@19' AS DATE);

์œ„์˜ ๋„ค ๋ฌธ์žฅ ๋ชจ๋‘ ๊ฐ™์€ ๊ฒฐ๊ณผ

  • ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ ํ•จ์ˆ˜ CONCAT
    • ์ธ์ž์— ์ˆซ์ž๊ฐ€ ๋“ค์–ด์žˆ์–ด๋„ ๋ฌธ์ž๋กœ ํ˜•๋ณ€ํ™˜ ์ผ์–ด๋‚จ.
    • CAST์™€ CONVERT๊ฐ€ ๋ช…์‹œ์  ํ˜•๋ณ€ํ™˜, CONCAT์ด ๋ฌต์‹œ์ /์•”์‹œ์ /์ž๋™ํ˜•๋ณ€ํ™˜
SELECT CONCAT('๋ฌธ์ž์—ด','์—ฐ๊ฒฐํ•˜๊ธฐ', '1');
SELECT CONCAT('๋ฌธ์ž์—ด','์—ฐ๊ฒฐํ•˜๊ธฐ', 1);

์œ„์˜ ๋‘ ๋ฌธ์žฅ๋„ ๊ฐ™์€ ๊ฒฐ๊ณผ

๋‚ด์žฅ ํ•จ์ˆ˜(์ œ์–ด)

  • IF(์ˆ˜์‹, ์ฐธ, ๊ฑฐ์ง“)
    • ์ˆ˜์‹์ด ์ฐธ์ด๋ฉด ๋‘๋ฒˆ์งธ ์ธ์ˆ˜ ๋ฐ˜ํ™˜, ๊ฑฐ์ง“์ด๋ฉด ์„ธ ๋ฒˆ์งธ ์ธ์ˆ˜ ๋ฐ˜ํ™˜
SELECT IF(1>2, '์ฐธ', '๊ฑฐ์ง“');

  • IFNULL(์ˆ˜์‹1, ์ˆ˜์‹2)
    • ์ˆ˜์‹1์ด NULL์ด ์•„๋‹ˆ๋ฉด ์ˆ˜์‹2, NULL์ด๋ฉด ์ˆ˜์‹1 ๋ฐ˜ํ™˜
SELECT IFNULL(NULL, '์ฐธ'), IFNULL(10, '๊ฑฐ์ง“');

  • NULLIF(์ˆ˜์‹1, ์ˆ˜์‹2)
    • ์ˆ˜์‹1๊ณผ ์ˆ˜์‹2 ๊ฐ™์œผ๋ฉด NULL๋ฐ˜ํ™˜, ๋‹ค๋ฅด๋ฉด ์ˆ˜์‹1 ๋ฐ˜ํ™˜
SELECT NULLIF(10,10), NULLIF(10,20);

  • CASE WHEN ELSE END
    • CASE๋Š” ์—ฐ์‚ฐ์ž
    • ๋‹ค๋ฅธ ์–ธ์–ด์˜ switch๋ฌธ๊ณผ ๋น„์Šท
SELECT CASE 2
	WHEN 1 THEN '1'
    WHEN 2 THEN '2'
    WHEN 3 THEN '3'
    ELSE 'NULL'
END;

 

728x90