简体   繁体   中英

Order by left outer join union right outer join

I got this sql query:

SELECT * 
FROM groups
LEFT OUTER JOIN group_questions
ON groups.id = group_questions.group_id 
WHERE group_questions.group_id = 1 ORDER BY group_questions.id DESC
UNION
SELECT * 
FROM groups
RIGHT OUTER JOIN group_questions 
ON groups.id = group_questions.group_id 
WHERE group_questions.group_id = 1 ORDER BY group_questions.id DESC

I'm trying to order it by doing this ORDER BY group_questions.id DESC like in the example above. But when I add it to the query it doesn't work at all. I've tried to search for an example but was unable to find one. Anyone here got an idea?

(
SELECT * 
FROM groups
LEFT OUTER JOIN group_questions
ON groups.id = group_questions.group_id 
WHERE group_questions.group_id = 1
)
UNION
(
SELECT * 
FROM groups
RIGHT OUTER JOIN group_questions 
ON groups.id = group_questions.group_id 
WHERE group_questions.group_id = 1 
)
ORDER BY id DESC

You must sort combined rowset after UNION. And you must refer to the column name of combined rowset (which now does not refer to any source table of any separate subquery).

In this particular case the parenthesis wrapped separate subqueries are formally excess and may be removed. But I recommend to use them always - this removes possible ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM