1. MySQL
Union ~ 공식문서 MySQL SQL 끝
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
WHERE절은 집계 함수를 사용하여 계산된 결과에 대해 조건을 적용하지 못하기 때문에 HAVING 사용
집계 함수란?
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
true
반환(=SELECT 문에 지정된 column 값)SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
ProductID
가 하나라도 있으면 해당 ProductID
로 Products
에서 ProductName
을 반환ProductID
가 모두 Quantity가 10인 경우에 해당 ProductID
로 Products
에서 ProductName
을 반환ProductID
가 모두 10이 아니라면 0
을 반환INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
INSERT INTO B
SELECT * FROM A;
IFNULL(expr1, expr2)
COALESCE(value1, value2, ..., valueN)
SUBSTRING_INDEX(email, '@', 1)
SUBSTRING_INDEX(email, '@', 2)
SUBSTRING_INDEX(email, '@', -1)
SUBSTRING(문자열, 출력할 첫 글자의 위치, 출력하고 싶은 글자 수)
CASE
WHEN 조건1 THEN 결과1
WHEN 조건2 THEN 결과2
...
ELSE 기본결과
END
with lecture_done as (
select enrolled_id, count(*) as cnt_done from enrolleds_detail ed
where done = 1
group by enrolled_id
), lecture_total as (
select enrolled_id, count(*) as cnt_total from enrolleds_detail ed
group by enrolled_id
)
select a.enrolled_id, a.cnt_done, b.cnt_total from lecture_done a
inner join lecture_total b on a.enrolled_id = b.enrolled_id
SELECT
ed.enrolled_id,
COUNT(CASE WHEN ed.done = 1 THEN 1 END) AS cnt_done,
COUNT(*) AS cnt_total
FROM
enrolleds_detail ed
GROUP BY
ed.enrolled_id;
select enrolled_id,
sum(done) as cnt_done,
count(*) as cnt_total
from enrolleds_detail ed
group by enrolled_id;
두 개 이상의 테이블 간에 JOIN을 수행하지 않고도 원하는 데이터 검색 가능
너무 많은 서브쿼리 사용은 성능에 부정적인 영향을 미칠 수 있음
select domain, count(*) as cnt from (
select SUBSTRING_INDEX(email,'@',-1) as domain from users
) a
group by domain
SELECT SUBSTRING_INDEX(u.email, '@', -1) as domain, COUNT(*) as cnt_domain FROM users u
group by domain