从带有DISTINCT字段的表中选择字段

时间:2013-08-10 12:11:53

标签: mysql distinct

我有一个这种类型的表

| user | parents | sons |

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

我写这个查询:

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

它有效! 因此它给出了重复用户的结果。 如何使用(parentsEd + sonsEd)DESC 订购DISTINC用户?

1 个答案:

答案 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`