为什么我的费用没有按降序显示?

时间:2015-07-07 05:48:13

标签: mysql sql

我已经编写了下面的查询,它似乎工作正常并返回正确的行数。但我需要成本'列按降序排列,不是。

SELECT check_out_interval, scan_code, c.cost, SUBSTR(title, 1, 30) AS 'Title'
FROM collection c LEFT JOIN biblio b ON 
     c.book_id = b.book_id
WHERE c.cost > (SELECT AVG(cost)
                FROM collection
                WHERE check_out_interval = check_out_interval
                ORDER BY check_out_interval, cost DESC);

3 个答案:

答案 0 :(得分:1)

在外部查询中移动order by子句。 目前它应用于内部查询,不需要它。

SELECT check_out_interval, scan_code, c.cost, SUBSTR(title, 1, 30) AS 'Title'
FROM collection c LEFT JOIN biblio b ON 
     c.book_id = b.book_id
WHERE c.cost > (SELECT AVG(cost)
                FROM collection
                WHERE check_out_interval = check_out_interval
                ) ORDER BY check_out_interval, cost DESC;

答案 1 :(得分:0)

order clause保留在主查询中而不是子查询

SELECT 
check_out_interval, scan_code, c.cost, SUBSTR(title, 1, 30) AS 'Title' 
FROM collection 
c LEFT JOIN biblio b ON c.book_id = b.book_id 
WHERE c.cost > 
(SELECT AVG(cost) FROM collection WHERE check_out_interval = check_out_interval)
ORDER BY check_out_interval, c.cost DESC;

答案 2 :(得分:0)

由于您希望结果排序的列属于外部查询中的Object,因此您必须在外部查询中保留ORDER BY子句。 像这样:

SELECT 
check_out_interval, scan_code, c.cost, SUBSTR(title, 1, 30) AS 'Title' 
FROM collection 
c LEFT JOIN biblio b ON c.book_id = b.book_id 
WHERE c.cost > 
(SELECT AVG(cost) FROM collection WHERE check_out_interval = check_out_interval)
ORDER BY check_out_interval, c.cost DESC;

了解更多信息请查看here