在GROUP BY之前按顺序排序

时间:2012-08-23 12:37:15

标签: mysql group-by sql-order-by

在按ap_status分组之前,我如何按此顺序'n', 'p', 'd', 'c', 'b', 'x'product_id订购所有行?

删除GROUP BY

时,此查询会正确排序
SELECT `account_id`, `product_id`, `product_name`, `ap_status`, count(`ap_id`) as `num` 
FROM (accounts_products_view)
WHERE `account_id` = 13
/*GROUP BY `product_id`*/
ORDER BY FIELD(`ap_status`, 'n', 'p', 'd', 'c', 'b', 'x') desc

所以我在查看了一些类似的问题之后尝试使用HAVING,但是这个问题在小组之前没有用到

SELECT account_id, product_id, product_name, ap_status, count(ap_id) as num,
CASE
WHEN ap_status = 'n' then 1
WHEN ap_status = 'p' then 2
WHEN ap_status = 'd' then 3
WHEN ap_status = 'c' then 4
WHEN ap_status = 'b' then 5
WHEN ap_status = 'x' then 6
END as `order`

FROM (accounts_products_view)
WHERE `account_id` = 13
GROUP BY product_id
HAVING `order` = MIN(`order`)

非常感谢任何建议

1 个答案:

答案 0 :(得分:1)

您可能想尝试:

SELECT *, count(`ap_id`) as `num` FROM (
        SELECT `account_id`, `product_id`, `product_name`, `ap_status`, `ap_id`
        FROM (accounts_products_view)
        WHERE `account_id` = 13
        /*GROUP BY `product_id`*/
        ORDER BY FIELD(`ap_status`, 'n', 'p', 'd', 'c', 'b', 'x') desc
    ) as res GROUP BY product_id

但要记住它是不正确的!如果使用group by,则需要使用聚合函数,例如SUM(),或者也可以在group by中指定字段。在您的示例中,您可能正确检索的字段是product_id而不是其他内容。由于MySQL的bug或者你在这个查询中没有得到异常,但在postgresql中你会得到异常。 如果您有2行具有相同的product_id和不同的ap_status,理论上您无法说明查询应返回哪一行。我想你已经发现在MySQL中会返回第一行,这就是你想在执行group by之前对行进行排序的原因。请记住,这是不正确的,非常黑客。

相关问题