我正在尝试执行在 select 语句中具有三元运算符的查询:
SELECT id,
memory_id,
CASE
WHEN word_to =? THEN word_from
ELSE word_to
end
FROM translations
WHERE word_to =?
OR word_from =?
如何使用 QueryBuilder
对象构建这样的查询?我试过:
public List<Translation> findMeanings(long wordId) {
try {
Dao<Translation, Long> translations = getDao(Translation.class);
QueryBuilder<Translation, Long> queryBuilder = translations.queryBuilder();
String id = Long.toString(wordId);
queryBuilder.selectRaw(DBColumns.ID, DBColumns.MEMORY_ID, "CASE WHEN word_to="+id+" THEN word_from ELSE word_to END");
queryBuilder.where().eq(DBColumns.WORD_TO, id).or().eq(DBColumns.WORD_FROM, id);
return queryBuilder.query();
} catch (SQLException e) {
Logger.error("db", e.getMessage(), e);
}
return new ArrayList<Translation>();
}
但是我得到一个异常(exception):
Could not compile this SELECT_RAW statement since the caller is expecting a SELECT statement. Check your QueryBuilder methods.
翻译类:
@DatabaseTable(tableName = DatabaseTables.TABLE_TRANSLATIONS)
public class Translation extends BaseEntity {
@DatabaseField(foreign = true, foreignColumnName = DBColumns.ID, columnName = DBColumns.WORD_TO)
private Word wordTo;
@DatabaseField(foreign = true, foreignColumnName = DBColumns.ID)
private Memory memory;
//...
其中 BaseEntity 是:
public class BaseEntity {
@DatabaseField(generatedId = true, unique = true)
protected long id;
//....
最佳答案
Could not compile this SELECT_RAW statement since the caller is expecting a SELECT statement. Check your QueryBuilder methods.
一旦调用 qb.selectRaw(...)
,您将需要使用 qb.queryRaw(...)
而不是 query( )
。 javadocs for selectRaw(...)
中提到了这一点:
Add raw columns or aggregate functions (COUNT, MAX, ...) to the query. This will turn the query into something only suitable for the Dao.queryRaw(String, String...) type of statement. This can be called multiple times to add more columns to select.
通常 selectRaw(...)
与某种聚合函数一起使用,如 COUNT()
或 MAX()
并且是因此与 query()
返回的实体类型不兼容。
关于android - 选择语句中的三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472850/