具有不同和order_by的记录的排序

问题描述 投票:0回答:1

我有这个查询,其中存在order_bydistinct字段,但两者都有不同的字段。查询是:

from(h in model, order_by: [desc: h.name], distinct: [asc: h.id]

返回的记录为sorted by distinct and not by order_by

我希望记录按name而不是id排序。

我希望每个记录都基于其主键来区分,但还要按名称字段进行排序。

有任何解决方法吗?谢谢。

elixir ecto
1个回答
0
投票

根据posgresql docs sql distinct,DISTINCT ON表达式必须与最左边的ORDER BY表达式匹配。

[下面的解决方法可能对您有所帮助

from(
  h in model,
  group_by: h.id,
  order_by: [desc: max(h.name)],
  select: %model{
    id: h.id,
    name: max(h.name)
  }
)

如果需要向select子句添加更多字段,则应使用与模型名称字段相同的技术将这些字段添加到order_by子句中>

© www.soinside.com 2019 - 2024. All rights reserved.