我想按降序列出按另一个表中一列的总和排序的实体。
entities
---------------------------------------
| id | name | created_at | updated_at |
---------------------------------------
| 1 | foo | ...
| 2 | bar | ...
other_table
----------------------
| entity_id | amount |
| 1 | 35 |
| 1 | 1 |
| 2 | 125 |
result
---------------------------------------
| id | name | created_at | updated_at |
---------------------------------------
| 2 | bar | ...
| 1 | foo | ...
不幸的是,这不可能将子查询传递给Ebean的desc()方法。
String sql = "SELECT SUM(amount)";
sql += " FROM other_table";
sql += " WHERE entities.id = other_table.entity_id";
RawSql rawSql = RawSqlBuilder.parse(sql).create();
Query<OtherTable> subQuery = Ebean.createQuery(OtherTable.class)
.setRawSql(rawSql);
List<Entity> list = Ebean.find(Entity.class)
.query().where()
.orderBy().desc(subQuery) // <- should by allowed
.setMaxRows(8)
.findList();
执行此类查询非常常见,所以我猜有一种明显的方法可以做到这一点,但我找不到它。