简体   繁体   中英

Sorting union result set of two table in mysql

I have two tables which are totally different by field and data but I want sorted data from both the tables. I have use union clause for that purpose and I am successful to fetch the result set but unable to sort the data. I have tried so many tricks but fail.

My query is -

  (SELECT amount FROM `purchase` order by amount desc limit 0, 10 )
UNION
(SELECT total_price as amount from `item` order by total_price desc limit 0, 10) order by amount desc

the result is -

-----------   
amount
-----------
9999.000
9998.000
999.000
9730
7750
7700
7600
6881
20000
13400
10250
10000

The result is OK but you can see that data is not sort by amount, it is sorted by table. But I want highest at the top ie 20000 and so on. Can anyone tell me what change I have to make in the query to achieve the result.

Try this query:

SELECT   * 
FROM     ( 
            SELECT cast(amount AS DECIMAL(10,2)) as amount 
            FROM   `purchase` limit 0, 10 
            UNION 
            SELECT total_price AS amount 
            FROM   `item` limit 0, 10) a 
ORDER BY amount DESC

SAMPLE DEMO

It seems that one of (or both) amount and total_price is text type. How about cast like this:

(SELECT amount + 0 AS amount FROM `purchase` order by amount desc limit 0, 10)
UNION
(SELECT total_price + 0 AS amount from `item` order by total_price desc limit 0, 10)
ORDER BY amount desc

If xxx + 0 not working, use CAST(total_price AS SIGNED INTEGER) .

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