简体   繁体   中英

How do you ORDER a UNION in MySQL?

I would like to know, how can we ordered the list (DESC) in Union based mysql_query, We are getting output when we fetch this query in PHP/ MYSQL. but we just simply put the order by in this query.

 (SELECT info.id 
 FROM info, 1_all 
 WHERE 1_all.id = info.id and 1_all.table_type = 'disp'  AND 1_all.year = '$year' AND  info.category IN (1,2,3) AND info.area IN (2,5,6)  
 GROUP BY resinfo.id ) 
UNION ALL 
 (SELECT info.id 
 FROM info, 2_all 
 WHERE 2_all.id = info.id and 2_all.table_type = 'disp' AND 2_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6) 
 GROUP BY info.id)

To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. The following example uses both clauses:

 (SELECT a FROM t1 WHERE a=10 AND B=1) UNION (SELECT a FROM t2 WHERE a=11 AND B=2) ORDER BY a LIMIT 10; 

http://dev.mysql.com/doc/refman/5.5/en/union.html

You can make an subquery like this:

SELECT info.id
FROM
(
  (SELECT info.id 
   FROM info, 1_all 
   WHERE 1_all.id = info.id and 1_all.table_type = 'disp'  AND 1_all.year = '$year' AND     info.category IN (1,2,3) AND info.area IN (2,5,6)  
   GROUP BY resinfo.id ) 
  UNION ALL 
  (SELECT info.id 
   FROM info, 2_all 
   WHERE 2_all.id = info.id and 2_all.table_type = 'disp' AND 2_all.year = '$year' AND info.category IN (1,2,3) AND info.area IN (2,5,6) 
   GROUP BY info.id)
) as all
order by id desc;

I don't know if MySQL engine accepts it, but other engins such as SQL Server allow you to add an order by clause at the end :

SELECT info.id 
 FROM info, 1_all 
 WHERE 1_all.id = info.id and 1_all.table_type = 'disp'  AND 1_all.year = '$year' AND      info.category IN (1,2,3) AND info.area IN (2,5,6)  
 GROUP BY resinfo.id
UNION ALL 
 SELECT info.id 
 FROM info, 2_all 
 WHERE 2_all.id = info.id and 2_all.table_type = 'disp' AND 2_all.year = '$year' AND     info.category IN (1,2,3) AND info.area IN (2,5,6) 
 GROUP BY info.id
ORDER BY info.id DESC;

If your database engine doesn't accept it, maybe your best bet is to create a view based on your union query and then have a query on this view with your order by.

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