在 OrmLite 中使用 SELECT DISTINCT ON

Use SELECT DISTINCT ON with OrmLite

我尝试编写此代码以使用 SELECT DISTINCT ON:

            var q = Db.From<WatchedUrlScanResult>();
            q.Join<WatchedUrlRecord>()
                .Where<WatchedUrlRecord>(x => x.TargetDomainRecordId == request.TargetDomainId)
                .And(x => x.ScanDate < fromEnd)
                .OrderBy(x => x.WatchedUrlRecordId)
                .OrderByDescending(x => x.ScanDate);

            q.SelectExpression = q.SelectExpression.Replace("SELECT",
                    $"SELECT DISTINCT ON ({q.Column<WatchedUrlScanResult>(x => x.WatchedUrlRecordId)})");

            var fromSnapshot = Db.Select<WatchedUrlScanResult>(q);

在调试器中,它显示已为 SelectExpression 设置的值,但运行的实际 SQL 只是 SELECT,没有 DISTINCT ON

我试过了:

q.Select(q.SelectExpression.Replace("SELECT",
                    $"SELECT DISTINCT ON ({q.Column<WatchedUrlScanResult>(x => x.WatchedUrlRecordId)})"));

但我得到:

Potential illegal fragment detected

是否可以在不将完整查询设为字符串的情况下执行此操作? (在完整的字符串查询中使用 {q.Column<Table>(x => x.ColumnName)} 很好,但与流利的语法相比可读性差)

如果您想在 OrmLite 中使用其 SqlExpression<T> 执行 SELECT DISTINCT 查询,您将使用 SelectDistinct() API,例如:

var results = Db.Select(q.SelectDistinct());

但是当您尝试执行自己的自定义 SQL 不同查询时,您需要使用 Custom SQL APIs,例如:

var sql = q.ToSelectStatement().Replace(what,with);
var results = Db.SqlList<WatchedUrlScanResult>(sql);