在mysql中对两个表的联合结果集进行排序

时间:2014-10-06 06:12:43

标签: php mysql sorting union

我有两个表,它们完全不同于字段和数据,但我希望从两个表中分类数据。我为此目的使用了union子句,并且我成功获取结果集但无法对数据进行排序。我尝试了很多技巧但却失败了。

我的查询是 -

  (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

结果是 -

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

结果没问题,但是您可以看到数据不是按数量排序,而是按表排序。但我想要在最高处,即20000,依此类推。任何人都可以告诉我在查询中我必须做出哪些改变才能实现结果。

2 个答案:

答案 0 :(得分:0)

尝试此查询:

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

答案 1 :(得分:0)

amounttotal_price中的一个(或两个)似乎是文本类型。怎么样这样投射:

(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

如果xxx + 0无效,请使用CAST(total_price AS SIGNED INTEGER)