티스토리 뷰

SQL

[SQL] 기초 공부 3일차

iblue 2022. 1. 6. 18:16

SELECT *
FROM orders
     INNER JOIN customers ON orders.customerid = customers.customerid
     INNER JOIN shippers ON orders.shipperid = shippers.shipperid

INNER JOIN 두 테이블에 공통된 칼럼을 중심으로 결합

단, primay key 불일치 등 결합할 수 없는 문제가 발생할 수도 있다 → ERD 를 보고 판단

 

SELECT *
FROM customers
     LEFT JOIN orders ON customers.customerid = orders.customerid
     WHERE orderid IS NULL

LEFT JOIN 왼쪽 테이블을 기준으로 결합한다

위 코드의 경우, customers 테이블을 기준으로 orders 테이블을 결합한다

→ 한번도 주문한 적 없는 고객의 정보도 불러옴

* NULL 값을 찾을 땐 IS NULL 이라고 작성한다

 

관련 연습문제

https://leetcode.com/problems/customers-who-never-order/

 

Customers Who Never Order - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

연습문제

https://leetcode.com/problems/employees-earning-more-than-their-managers/

 

Employees Earning More Than Their Managers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

-- query to find the employees who earn more than their managers.

SELECT e.name as employee
FROM employee AS e
INNER JOIN employee as m ON e.managerid = m.id
WHERE e.salary > m.salary

SELF JOIN 하나의 테이블을 결합한다

* 테이블의 칼럼을 자세히 살펴봐야 한다.

* 기준점이 되는 칼럼 지정후, 각 테이블 이름을 설정할 것

 

https://leetcode.com/problems/rising-temperature/

 

Rising Temperature - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

SELECT today.id
FROM weather as today
INNER JOIN weather as yesterday ON DATE_ADD(yesterday.recordDate, INTERVAL 1 DAY) = today.recordDate
WHERE today.temperature > yesterday.temperature

* 날짜 더하는 함수 DATE_ADD(칼럼명, INTERVAL 수 단위)

단위 SECOND, MINUTE, HOUR, DAY, MONTH, YEAR

수 +/- 둘 다 가능 (-1 입력시 DATE_SUB 와 같은 기능)

'SQL' 카테고리의 다른 글

[SQL] 기초 공부 4일차  (0) 2022.01.06
[SQL] 기초 공부 2일차  (0) 2022.01.04
[SQL] 기초 공부 1일차  (0) 2021.12.24
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함