UNION ALL 과 ORDER BY 섞어서 쓰기

by 조쉬 posted Aug 30, 2016
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄
각 게시판에 최근글을 모아서 리스트를 만들려고 시도했던 적이있다.
UNION ALL 과 ORDER BY 구문을 쓰다가 에러났는데 해결되었다.
-- 에러구문
(SELECT TOP 1 No, Title, Idate FROM tbCellPhoto ORDER BY Idate DESC
UNION ALL
SELECT TOP 1 No, Title, Idate FROM tbExchange ORDER BY Idate DESC)
ORDER BY Idate DESC

-- 문법
SELECT ....
FROM (SELECT TOP 1 ...
FROM ...
ORDER BY ...) AS x
UNION ALL
SELECT ....
FROM (SELECT TOP 4 ...
FROM ...
ORDER BY ... DESC) AS y

-- 다음과 같이 적용시켯다
SELECT TOP * FROM (
select * from (SELECT TOP 5 No, Title, Idate, path = '/Border/CellPhoto' FROM tbCellPhoto ORDER BY No DESC) AS a1
UNION ALL
select * from (SELECT TOP 5 No, Title, Idate, path = '/Border/Confession' FROM tbConfession ORDER BY No DESC) AS a2
) AS a3
ORDER BY Idate DESC

Articles

1 2 3 4 5 6 7