我一直被类似的问题所困扰。尽管我使用的是 java,但我似乎找到了一些相关的东西,希望对您有所帮助:
// template : R2dbcEntityTemplate
final StatementMapper statementMapper = template.getDataAccessStrategy().getStatementMapper();
statementMapper.createSelect("table_name")
.distinct() // distinct!
.doWithTable((table, spec) -> {
// Do with table.
// See org.springframework.data.r2dbc.core.R2dbcEntityTemplate#doSelect or other.
return // return something
});
如果要对count函数进行去重,可能需要参考org.springframework.data.relational.core.sql.SimpleFunction
实现一个新的类,比如CountDistinctFunction
. 你可以参考这个:
/**
*
* Function: {@code COUNT(DISTINCT ... )}
*
* @see org.springframework.data.relational.core.sql.Functions
* @see org.springframework.data.relational.core.sql.SimpleFunction
* @author ForteScarlet
*/
public class CountDistinctFunction implements Expression {
private static final String FUNCTION_NAME = "COUNT";
private final List<Expression> expressions;
private CountDistinctFunction(List<Expression> expressions) {
this.expressions = expressions;
}
/** getInstance. */
public static CountDistinctFunction getInstance(Expression... expressions) {
return new CountDistinctFunction(Arrays.asList(expressions));
}
/**
* @see SimpleFunction#toString()
*/
@Override
public @NotNull String toString() {
return FUNCTION_NAME + "(DISTINCT " + StringUtils.collectionToDelimitedString(expressions, ", ") + ")";
}
/**
* @see SimpleFunction#getFunctionName()
*/
public String getFunctionName() {
return FUNCTION_NAME;
}
/**
* @see SimpleFunction#getExpressions()
*/
public List<Expression> getExpressions() {
return Collections.unmodifiableList(expressions);
}
/**
* @see org.springframework.data.relational.core.sql.AbstractSegment
*/
@SuppressWarnings("JavadocReference")
@Override
public void visit(@NotNull Visitor visitor) {
Assert.notNull(visitor, "Visitor must not be null!");
visitor.enter(this);
visitor.leave(this);
}
/**
* @see org.springframework.data.relational.core.sql.AbstractSegment
*/
@SuppressWarnings("JavadocReference")
@Override
public int hashCode() {
return toString().hashCode();
}
/**
* @see org.springframework.data.relational.core.sql.AbstractSegment
*/
@SuppressWarnings("JavadocReference")
@Override
public boolean equals(Object obj) {
return obj instanceof Segment && toString().equals(obj.toString());
}
}
并使用它:
R2dbcEntityTemplate template; = // template instance
final StatementMapper statementMapper = template.getDataAccessStrategy().getStatementMapper();
final StatementMapper.SelectSpec selectSpec = statementMapper.createSelect("your_table_name")
.withCriteria(criteria)
.doWithTable((table, spec) -> spec.withProjection(CountDistinctFunction.getInstance(table.column("id"))));
final PreparedOperation<?> operation = statementMapper.getMappedObject(selectSpec);
final Mono<Long> count = template.getDatabaseClient().sql(operation).map(r -> r.get(0, Long.class)).first();
虽然这篇文章已经很久了,但我会对此发表我的看法。如果有人碰巧看到它并且有更好的计划,那么也请告诉我,非常感谢!
(通过 DeepL 翻译)