[MYSQL] ๐ŸŒŸ LeetCode SQL

์ž„๋‚™ํ˜„ยท2022๋…„ 10์›” 11์ผ
0

SQL for DataBase

๋ชฉ๋ก ๋ณด๊ธฐ
4/4
post-thumbnail

LeetCode ๋ผ๋Š” ์‚ฌ์ดํŠธ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

https://leetcode.com/problemset/all/

์—ฌ๋Ÿฌ๊ฐ€์ง€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ถ€ํ„ฐ ํ•™์Šต ๋ฐ ์ธํ„ฐ๋ทฐ๊นŒ์ง€ ์—ฌ๋Ÿฌ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ณต๋ถ€๋ฅผ ํ•  ์ˆ˜ ์žˆ๋Š” ์‚ฌ์ดํŠธ์ž…๋‹ˆ๋‹ค.

์—ฌ๊ธฐ์„œ ์ €๋Š” SQL Study Plan ์„ ๋งค์ผ ํ•œ๋ฒˆ ํ•ด๋ณผ๊นŒ ํ•ฉ๋‹ˆ๋‹ค.

๊ทธ๋Ÿผ 1์ผ์ฐจ ์‹œ์ž‘ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.


1. ๐ŸŒŽ Big Countries


https://leetcode.com/problems/big-countries/?envType=study-plan&id=sql-i

๋ฌธ์ œ์—์„œ๋Š” ๋ฉด์ ์ด 3000000km2 ์ด์ƒ์ด๊ฑฐ๋‚˜ ์ธ๊ตฌ์ˆ˜๊ฐ€ 25000000๋ช… ์ด์ƒ์ธ ๋‚˜๋ผ๋ฅผ big countries๋กœ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.

์ด๋•Œ big countries๋ฅผ ์ฐพ์•„์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

SELECT
    name, population, area
FROM
    World
WHERE
    area >= 3000000 OR population >= 25000000
;

WHERE์ ˆ์— ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์กฐ๊ฑด์„ ๋„ฃ์–ด์„œ ์–ด๋ ต์ง€ ์•Š๊ฒŒ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค.



2. ๐ŸŒฎ Recyclable and Low Fat Products


https://leetcode.com/problems/recyclable-and-low-fat-products/?envType=study-plan&id=sql-i

๋ฌธ์ œ์˜ ์กฐ๊ฑด์€ low fat ์ด๋ฉด์„œ recyclable ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฝ‘์•„๋‚ด๋ผ๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

SELECT
    product_id
FROM
    Products
WHERE
    low_fats = 'Y' AND recyclable = 'Y'
;

๊ฐ„๋‹จํžˆ WHERE ์ ˆ์— ์กฐ๊ฑด์„ ๋‘˜ ๋‹ค ๋„ฃ์–ด์ฃผ์–ด์„œ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค.



3. ๐Ÿ“‹ Find Customer Referee


https://leetcode.com/problems/find-customer-referee/?envType=study-plan&id=sql-i

์•„๋ž˜์™€ ๊ฐ™์ด referee_id ๊ฐ€ 2๊ฐ€ ์•„๋‹Œ ์‚ฌ๋žŒ์˜ ์ด๋ฆ„๋งŒ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

SELECT
    name
FROM
    Customer
WHERE referee_id != 2 OR referee_id IS NULL
;

WHERE ์ ˆ์— referee_id ๊ฐ€ 2๊ฐ€ ์•„๋‹ˆ๋ฉด์„œ NULL๊ฐ’๋„ ํฌํ•จํ•˜๊ฒŒ๋” ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค.



4. ๐Ÿ™…โ€โ™€๏ธ Customers Who Never Order


https://leetcode.com/problems/customers-who-never-order/?envType=study-plan&id=sql-i

Orders ํ…Œ์ด๋ธ”์˜ customerId๋Š” Customers ํ…Œ์ด๋ธ”์˜ foregin key ์ž…๋‹ˆ๋‹ค.
์ด๋•Œ ์ฃผ๋ฌธํ•˜์ง€ ์•Š์€(Orders ํ…Œ์ด๋ธ”์— customerId์˜ ๊ฐ’์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š”) ์‚ฌ๋žŒ์„ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

SELECT
    name AS "Customers"
FROM
    Customers AS C
LEFT OUTER JOIN Orders AS O
ON C.id = O.customerId
WHERE O.customerId IS NULL
;

Customers ํ…Œ์ด๋ธ”๊ณผ Orders ํ…Œ์ด๋ธ”์„ ์ˆœ์„œ๋Œ€๋กœ LEFT OUTER JOIN ํ•˜์—ฌ ์ด๋•Œ ์ฃผ๋ฌธํ•˜์ง€ ์•Š์€ ์‚ฌ๋žŒ์„ ์ถ”์ถœํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, JOINํ•œ ํ…Œ์ด๋ธ”์˜ customerId๊ฐ€ NULL๊ฐ’์ธ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”์ถœํ•˜์—ฌ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค.


์ด์ƒ์œผ๋กœ 1์ผ์ฐจ ๊ณต๋ถ€๋ฅผ ๊ฐ„๋‹จํžˆ ๋งˆ์ณ๋ณด์•˜์Šต๋‹ˆ๋‹ค.

๋‚ด์ผ์€ 2์ผ์ฐจ๋ฅผ ํ•œ๋ฒˆ ํ•ด๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

profile
์ฝ”๋”ฉํ•˜๋Š” ์ˆ˜ํ•™๊ณผ

0๊ฐœ์˜ ๋Œ“๊ธ€