๐Ÿ˜ˆ ๊ต์ฐฉ ์ƒํƒœ๋ฅผ ์ˆ˜๋™์œผ๋กœ ์‹คํ–‰ํ•˜์ž! [SQL]

4276 ๋‹จ์–ด databasemysqlbeginnerssql

๐Ÿ’Ž ๊ต์ฐฉ์ƒํƒœ๋ž€?



์ด๊ฒƒ์€ ์—ฌ๋Ÿฌ ์‚ฌ์šฉ์ž๊ฐ€ ๊ฐ ์ž ๊ธˆ ํ•ด์ œ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๊ณ  ์˜๊ตฌ ์ž ๊ธˆ์ด ํ•ด์ œ๋˜์ง€ ์•Š๋Š” ์ƒํ™ฉ์ž…๋‹ˆ๋‹ค.

๐Ÿ’Ž ๊ต์ฐฉ์ƒํƒœ๋ฅผ ํ•ด๋ณด์ž



1๏ธโƒฃ ์ด ํ…Œ์ด๋ธ” ๋งŒ๋“ค๊ธฐ




-- schema
CREATE TABLE Lefty (
    Id INT NOT NULL AUTO_INCREMENT,
    Number INT,
    PRIMARY KEY(Id)
);
CREATE TABLE Righty (
    Id INT NOT NULL AUTO_INCREMENT,
    Number INT,
    PRIMARY KEY(Id)
);

-- data
INSERT INTO Lefty (Number) VALUES (1);
INSERT INTO Righty (Number) VALUES (1);


์™ผ์†์žก์ด ํ…Œ์ด๋ธ”


ID
์ˆซ์ž


1
1


์˜ค๋ฅธ์ชฝ ํ…Œ์ด๋ธ”


ID
์ˆซ์ž


1
1


2๏ธโƒฃ ์‹œ์ž‘ํ•˜์ž



1. ์ฒ˜์Œ์— ๋‘ ํ…Œ์ด๋ธ” ๋ชจ๋‘ ํŠธ๋žœ์žญ์…˜์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰, BLOCKING์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.

โ–ผ 2๋ช…์˜ ์‚ฌ์šฉ์ž(ํƒญ)๊ฐ€ ์ง€๊ธˆ ๋™์‹œ์— ๋ฌด์–ธ๊ฐ€๋ฅผ ์‹œ๋„ํ•œ๋‹ค๊ณ  ์ƒ์ƒํ•ด๋ณด์„ธ์š”.


2.์™ผ์ชฝ ํƒญ์—์„œ ์‹คํ–‰UPDATE Righty SET Number = Number+1;

๋ณด์‹œ๋‹ค์‹œํ”ผ UPDATE SQL์€ ๊ธฐ๋‹ค๋ฆฌ๋‹ค๊ฐ€... Righty๊ฐ€ ์ด์ „์— ์ž ๊ฒผ๊ธฐ ๋•Œ๋ฌธ์— ์™„๋ฃŒ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์˜์›ํžˆ ๊ธฐ๋‹ค๋ฆด๊ฑฐ์•ผ

3. order2 ์‹คํ–‰ ์ค‘ ์˜ค๋ฅธ์ชฝ ํƒญ์—์„œ ์‹คํ–‰UPDATE Lefty SET Number = Number+1;๊ทธ๋žฌ๋”๋‹ˆ ๊ต์ฐฉ์ƒํƒœ ์—๋Ÿฌ๊ฐ€ ๋–ด๋‹ค!! ๋‘ ์‚ฌ์šฉ์ž ๋ชจ๋‘ ์ง€๊ธˆ ๊ฐ ์ž ๊ธˆ ํ•ด์ œ๋ฅผ ๊ธฐ๋‹ค๋ฆฝ๋‹ˆ๋‹ค.


๋ชจ๋‘๊ฐ€ ๋ˆ„๊ตฐ๊ฐ€๊ฐ€ ๋‹ฌ๋ฆฌ๊ธฐ๋ฅผ ๋ฉˆ์ถœ ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์— ์•„๋ฌด๋„ ๋‹ฌ๋ฆฌ๊ธฐ๋ฅผ ๋ฉˆ์ถœ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค!

If deadlock error didn't appear, you could change autocommit setting



mysql> SELECT @@session.autocommit;
+----------------------+
| @@session.autocommit |
+----------------------+
|                    1 |
+----------------------+

-- change autocommit to 0
SET autocommit=0;


์ฝ์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜Ž


(์•ž์œผ๋กœ ์ฐธ๊ณ ๋งŒ ํ•˜์„ธ์š”)
๋ชจ๋‘๊ฐ€ ๋ˆ„๊ตฐ๊ฐ€๊ฐ€ ๋‹ฌ๋ฆฌ๊ธฐ๋ฅผ ๋ฉˆ์ถœ ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์— ์•„๋ฌด๋„ ๋‹ฌ๋ฆฌ๊ธฐ๋ฅผ ๋ฉˆ์ถœ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค!
-> ใฟใ‚“ใช่ตฐใฃใฆใ‚‹, ๆญขใพใ‚‹ๆกไปถใฏ่ชฐใ‹ใŒๆญขใพใฃใŸใ‚‰.ใงใ‚‚ใฟใ‚“ใช่ชฐใ‹ใŒๆญขใพใ‚‹ใฎๅพ…ใฃใฆใ‚‹ใ‹ใ‚‰ใ€่ชฐใ‚‚ๆญขใพใ‚Šใพใ›ใ‚“.

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ