0

我有一张这种类型的桌子

| 用户 | 父母| 儿子 |

  • 可以为 NULL 的父母和儿子的列。
  • 用户列可以包含重复

我写了这个查询:

SELECT user, COALESCE(parents, 0) AS parentsEd, COALESCE(sons, 0) AS sonsEd 
  FROM my_table 
  ORDER BY (parentsEd + sonsEd) DESC

它有效!所以它给出了重复用户的结果。如何使用(parentsEd + sonsEd) DESC ORDER 拥有 DISTINC 用户?

4

1 回答 1

1

在 order 子句之前使用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`
于 2013-08-10T12:56:12.457 回答