SELECT *
FROM Products
WHERE price <=5
UNION
SELECT *
FROM Products
WHERE price >= 200
FULL OUTER JOIN을 구현하고자 할 때,
LEFT JOIN 과 RIGHT JOIN을 UNION으로 묶어 주면 된다.
SELECT *
FROM Custoemrs
LEFT JOIN Orders ON Custoemrs.custoemrId = Orders.CustomerId
UNION
SELECT *
FROM Custoemrs
RIGHT JOIN Orders ON Custoemrs.custoemrId = Orders.CustomerId
HackerRank: Symmetric Pairs
문제의 요구사항은 다음과 같다.
Two pairs (X1, Y1) and (X2, Y2) are said to be symmetricpairs if X1 = Y2 and X2 = Y1.
Write a query to output all such symmetricpairs in ascending order by the value of X. List the rows such that X1 ≤ Y1.
위의 조건을 만족시키는 경우는 X1=Y1=X2=Y2이거나
X1 < Y1, X2 > Y2이면서 symmetric 한 경우이다.
두 경우의 조건을 각각 구한 후 UNION으로 합한다.
SELECT x, y
FROM Functions
where x = y
GROUP BY x, y
HAVING COUNT(*) = 2
UNION
SELECT f1.x, f1.y
FROM Functions AS f1
INNER JOIN Functions AS f2 ON f1.x = f2.y AND f1.y = f2.x
WHERE f1.x < f1.y
ORDER BY x -- UNION을 사용하는 경우 마지막에 ORDER BY를 써줘야 정렬이 된다.