Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加DistinctBy支持 #1680

Closed
ZUOXIANGE opened this issue Dec 8, 2023 · 6 comments
Closed

添加DistinctBy支持 #1680

ZUOXIANGE opened this issue Dec 8, 2023 · 6 comments

Comments

@ZUOXIANGE
Copy link

Feature 特性

_freeSql.Select<TestTable>().DistinctBy(x => new{ Column1, Column2 }).ToList();

PostgreSQL distinct on 用法

使用场景

根据某几个字段去重,但是又可以查询出未去重字段的值

@2881099
Copy link
Collaborator

2881099 commented Dec 8, 2023

简单写了下,你用下面扩展方法 ToSql() 试试看?

public static ISelect<T1> DistinctOn<T1>(this ISelect<T1> query, Expression<Func<T1, object>> selector)
{
  var select = query as FreeSql.PostgreSQL.Curd.PostgreSQLSelect<T1>;
  if (select == null) throw new Exception($"{nameof(DistinctOn)} 是 FreeSql.Provider.PostgreSQL 特有的功能");
  var s0p = select as Select0Provider;
  var orderByOld = s0p._orderby;
  var orderByNew = "";
  try
  {
    s0p._orderby = null;
    select.OrderBy(selector);
    orderByNew = s0p._orderby;
  }
  finally
  {
    s0p._orderby = orderByOld;
  }
  if (orderByNew.StartsWith(" \r\nORDER BY "))
    s0p._select = $"{s0p._select} distinct on({orderByNew.Substring(12)}) ";
  return select;
}

@2881099
Copy link
Collaborator

2881099 commented Dec 8, 2023

见楼上

@ZUOXIANGE
Copy link
Author

命名还是建议用DistinctBy,虽然和数据库函数不一致,但是和Enumerable.DistinctBy方法保持了一致.这样以后可以扩展到其他数据库.目前我使用中的clickhouse和PostgreSQL是支持这个功能

@2881099
Copy link
Collaborator

2881099 commented Dec 8, 2023

这种方法暂时只能用扩展方式提供,不加入正式 API。

个人建议以数据库命名比较好,Enumerable.DistinctBy 了解的人不多(例如我从未用过,更不知道它做什么的)

@ZUOXIANGE
Copy link
Author

ZUOXIANGE commented Dec 8, 2023

那先待定吧,可以参考EF对于这个的支持进度 dotnet/efcore#27470

目前我是通过写原生sql解决的

@2881099
Copy link
Collaborator

2881099 commented Dec 8, 2023

上面我发的扩展方法试了没有

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants