如何在 MySQL 中按 SUM() 排序?
我有一张表:ID 名称 c_counts f_counts"
I have a table: "ID name c_counts f_counts "
我想通过 sum(c_counts+f_counts)
对所有记录进行排序但这不起作用:
and I want to order all the record by sum(c_counts+f_counts)
but this doesn't work:
SELECT * FROM table ORDER BY sum(c_counts+f_counts) LIMIT 20;
推荐答案
别忘了,如果您混合分组(即 SUM)字段和非分组字段,则需要对非分组字段之一进行 GROUP BY字段.
Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.
试试这个:
SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname
或者这个:
SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2
而且你总是可以像这样进行派生查询:
And you can always do a derived query like this:
SELECT
f1, f2
FROM
(
SELECT SUM(x+y) as f1, foo as F2
FROM tablename
GROUP BY f2
) as table1
ORDER BY
f1
多种可能性!
相关文章