DevLog ๐Ÿ˜ถ

[MySQL] Error 1093: You can't specify target table for update in FROM clause ๋ณธ๋ฌธ

๊ฐœ๋ฐœ์ผ์ง€

[MySQL] Error 1093: You can't specify target table for update in FROM clause

dolmeng2 2023. 5. 29. 13:53

๐ŸŒฑ ๋ฌธ์ œ ์ƒํ™ฉ 

์‚ฌ์šฉ์ž์˜ ์š”์ฒญ์œผ๋กœ๋ถ€ํ„ฐ ๋ฐ›์€์žฅ๋ฐ”๊ตฌ๋‹ˆ ์•„์ด๋””์™€ ์‚ฌ์šฉ์ž์˜ ์•„์ด๋””๊ฐ€ ์ผ์น˜ํ•˜๋Š” ๊ฒฝ์šฐ์—๋งŒ ์ œ๊ฑฐํ•˜๊ธฐ ์œ„ํ•ด ์•„๋ž˜์™€ ๊ฐ™์€ ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ–ˆ๋‹ค.

DELETE FROM cart_item AS c
WHERE c.id
IN (
    SELECT ci.id FROM cart_item AS ci
    JOIN member AS m ON ci.member_id = m.id
    AND ci.id IN (6, 8) AND m.id = 1
);

ํ•˜์ง€๋งŒ, ๋‹ค์Œ๊ณผ ๊ฐ™์ด target table (cart_item)์˜ c์— ๋Œ€ํ•ด์„œ ์—…๋ฐ์ดํŠธ๋ฅผ ํ•  ์ˆ˜ ์—†๋‹ค๋Š” ๋ฌธ๊ตฌ๊ฐ€ ๋‚˜์™”๋‹ค.

 


 

๐ŸŒฑ ์›์ธ

MySQL์—์„œ๋Š” update, delete ์‹œ์— ์ž๊ธฐ ์ž์‹ ์˜ ํ…Œ์ด๋ธ” ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ”๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐœ์ƒํ•œ ์˜ค๋ฅ˜์˜€๋‹ค.

(์ฐธ๊ณ ๋กœ H2 ํ™˜๊ฒฝ์—์„œ๋Š” ์ž˜ ๋Œ์•„๊ฐ„๋‹ค. ์˜›๋‚ ์—๋„ ์ด๋Ÿฐ ์˜ค๋ฅ˜๊ฐ€ ๋‚ฌ์—ˆ๋Š”๋ฐ... ๊ธฐ๋กํ•˜์ง€ ์•Š์€ ์ž์˜ ์ตœํ›„ ๐Ÿ˜…)

 


๐ŸŒฑ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

IN ์ ˆ ๋‚ด๋ถ€์— ์กด์žฌํ•˜๋Š” ์„œ๋ธŒ ์ฟผ๋ฆฌ์— ๋Œ€ํ•ด์„œ ์ž„์‹œ ํ…Œ์ด๋ธ”๋กœ ๋งŒ๋“  ๋‹ค์Œ์—, ํ•ด๋‹น ํ…Œ์ด๋ธ”์„ ์ฐธ์กฐํ•˜๋„๋ก ๋งŒ๋“ค๋ฉด ๋œ๋‹ค.

DELETE FROM cart_item AS c
WHERE c.id
IN (
    SELECT cart_item_temp.id
    FROM
    (
        SELECT ci.id AS id FROM cart_item AS ci
        JOIN member AS m ON ci.member_id = m.id
        AND ci.id IN (6, 8) AND m.id = 1
    ) cart_item_temp
);

์ฝ”๋“œ๊ฐ€ ๋ณต์žกํ•˜๊ธฐ๋Š” ํ•˜์ง€๋งŒ, h2์™€ mysql ํ™˜๊ฒฝ ๋ชจ๋‘์—์„œ ์ž˜ ๋™์ž‘ํ•˜๋„๋ก ๋งŒ๋“œ๋ ค๋ฉด ์–ด์ฉ” ์ˆ˜ ์—†๋Š” ์„ ํƒ์ด์—ˆ๋‹ค.

DELETE c
FROM cart_item AS c
JOIN member AS m ON c.member_id = m.id
WHERE c.id IN (6, 8) AND m.id = 1;

๋‹จ์ˆœํ•˜๊ฒŒ ์ด๋ ‡๊ฒŒ ์กฐ์ธ์„ ํ•ด๋„ ๋˜์ง€๋งŒ, h2์—์„œ๋Š” delete ์ ˆ์— ๋Œ€ํ•ด์„œ ๋ณ„์นญ์„ ์ง€์›ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์‚ฌ์šฉํ•  ์ˆ˜๊ฐ€ ์—†์—ˆ๋‹ค...

h2 mode๋ฅผ MySQL๋กœ ํ•˜๋”๋ผ๋„ ์ด๋Ÿฐ ์ฟผ๋ฆฌ์— ๋Œ€ํ•ด์„œ๋Š” ์™„์ „ ๋™์ผํ•˜๊ฒŒ ๋™์ž‘ํ•˜์ง€๋Š” ์•Š๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

Comments