我有一个这种类型的表
| user | parents | sons |
带
我写这个查询:
SELECT user, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd
FROM my_table
ORDER BY (parentsEd + sonsEd) DESC
它有效! 因此它给出了重复用户的结果。 如何使用(parentsEd + sonsEd)DESC 订购DISTINC用户?
答案 0 :(得分:1)
在订单子句之前使用GROUP BY
,如果您想首先订购结果,请将它们分组然后使用subselect
SELECT `user`, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd
FROM my_table GROUP BY `user` ORDER BY (parentsEd + sonsEd) DESC
SELECT DISTINCT `user`, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd
FROM my_table ORDER BY (parentsEd + sonsEd) DESC
SELECT a.* FROM (
SELECT DISTINCT `user`, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd
FROM my_table ORDER BY (parentsEd + sonsEd) DESC ) a GROUP BY a.`user`