๐Ÿ’ SQL (Programmers)/Select

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][MySQL] ์—…๊ทธ๋ ˆ์ด๋“œ ๋œ ์•„์ดํ…œ ๊ตฌํ•˜๊ธฐ (level2)

์„ ๋‹ฌ 2024. 11. 20. 02:51
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

์•„์ดํ…œ์˜ ํฌ๊ท€๋„๊ฐ€ 'RARE'์ธ ์•„์ดํ…œ๋“ค์˜

๋ชจ๋“  ๋‹ค์Œ ์—…๊ทธ๋ ˆ์ด๋“œ ์•„์ดํ…œ์˜

์•„์ดํ…œ ID(ITEM_ID), ์•„์ดํ…œ ๋ช…(ITEM_NAME), ์•„์ดํ…œ์˜ ํฌ๊ท€๋„(RARITY)๋ฅผ ์ถœ๋ ฅํ•˜๋Š” SQL ๋ฌธ์„ ์ž‘์„ฑํ•ด ์ฃผ์„ธ์š”.

์ด๋•Œ ๊ฒฐ๊ณผ๋Š” ์•„์ดํ…œ ID๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์ฃผ์„ธ์š”.

 

์ฝ”๋“œ

select a.ITEM_ID, a.ITEM_NAME, a.RARITY
from ITEM_INFO a 
    join (
        select i.ITEM_ID as parent_id, t.ITEM_ID as child_id
        from ITEM_INFO i left join ITEM_TREE t on i.ITEM_ID = t.PARENT_ITEM_ID 
        where i.RARITY = 'RARE'
        ) b
    on a.ITEM_ID = b.child_id
order by a.ITEM_ID desc

 

ํ’€์ด

1. ํฌ๊ท€๋„๊ฐ€ RARE์ธ ์•„์ดํ…œ๋“ค์˜ id์™€, ๊ทธ ์•„์ด๋””์˜ ์ž์‹ id๋ฅผ ๋ฝ‘์•„๋‚ธ๋‹ค 

        select i.ITEM_ID as parent_id, t.ITEM_ID as child_id
        from ITEM_INFO i left join ITEM_TREE t on i.ITEM_ID = t.PARENT_ITEM_ID 
        where i.RARITY = 'RARE'

 

2. ๋ฐฉ๊ธˆ ๋ฝ‘์•„๋‚ธ ํ‘œ์—์„œ์˜ ์ž์‹ id์— ๋Œ€ํ•œ ์ •๋ณด๋“ค์„ ๊ฐ€์ ธ์˜จ๋‹ค (item_info ์™€ join)

select a.ITEM_ID, a.ITEM_NAME, a.RARITY
from ITEM_INFO a 
    join (๋ฐฉ๊ธˆ์ฝ”๋“œ) b
    on a.ITEM_ID = b.child_id
order by a.ITEM_ID desc

 

๋ฐ˜์‘ํ˜•