MySQL顺序通过不排序正确的数据

时间:2015-11-02 09:46:05

标签: mysql

我正在尝试使用以下查询从SUMed列对我的查询记录进行排序:

SELECT o.id_customer, CONCAT(c.firstname, ' ', c.lastname) AS 'name',
    COUNT(o.id_customer) AS 'repeat', FORMAT(SUM(o.total_products),2) AS 'amount'
FROM ps_orders AS o
LEFT JOIN ps_customer AS c ON o.id_customer = c.id_customer
WHERE o.current_state IN (2,4,5)
AND o.invoice_date BETWEEN '2015-01-01' AND '2015-12-31'
GROUP BY o.id_customer
ORDER BY amount DESC

上面的查询没有返回正确的数据,更具体地说,返回的记录没有正确排序。

有人能指出我正确的方向吗?非常感谢任何帮助。

干杯

3 个答案:

答案 0 :(得分:1)

您使用FORMAT方法格式化了金额

FORMAT返回字符串。

您的查询按数据类型字符串而不是数字

排序

答案 1 :(得分:0)

可能是导致问题的Join:以下引用可能会触发一些想法: http://dev.mysql.com/doc/refman/5.7/en/left-join-optimization.html

答案 2 :(得分:0)

您可以尝试使用子查询:

SELECT * 
FROM (
    SELECT o.id_customer, CONCAT(c.firstname, ' ', c.lastname) AS 'name',
        COUNT(o.id_customer) AS 'repeat', FORMAT(SUM(o.total_products),2) AS 'amount'
    FROM ps_orders AS o
    LEFT JOIN ps_customer AS c ON o.id_customer = c.id_customer
    WHERE o.current_state IN (2,4,5)
    AND o.invoice_date BETWEEN '2015-01-01' AND '2015-12-31'
    GROUP BY o.id_customer
) AS o
ORDER BY amount DESC