我有这个查询,其中存在order_by
和distinct
字段,但两者都有不同的字段。查询是:
from(h in model, order_by: [desc: h.name], distinct: [asc: h.id]
返回的记录为sorted by distinct and not by order_by
我希望记录按name
而不是id
排序。
我希望每个记录都基于其主键来区分,但还要按名称字段进行排序。
有任何解决方法吗?谢谢。
根据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子句中>