简体   繁体   中英

SQL Union sort by Union

I have query

SELECT id, name 
  FROM users 
  WHERE id !=2 
UNION 
SELECT id, name 
  FROM users2 
  WHERE id != 3;

I want that sort will be, 1 union orders + 2 union it's possible ?

Add a column to order on

SELECT id, name, 1 as unionOrder FROM users WHERE id !=2 
UNION 
SELECT id, name, 2 as unionOrder FROM users2 WHERE id != 3

ORDER BY unionOrder 

You can as well do like

(SELECT id, name 
  FROM users 
  WHERE id !=2
ORDER BY id)
UNION ALL
(SELECT id, name 
  FROM users2 
  WHERE id != 3
  ORDER BY id);

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