SQLiteQueryBuiler.setProjectionMap() 不影响 where 子句

SQLiteQueryBuiler.setProjectionMap() doesn't affect where clause

我有一个带有 ContentProvider class 的 Android 应用程序,它查询两个 tables,usersitems

users table 有以下列:

_id (primary key)
online (integer)

items table 有以下列:

_id (primary key)
user_id (foreign key, maps to users._id)
name (text)

然后我有一个查询 returns 两个 table 连接在一起的结果。在我的 ContentProvider 中,我使用此代码映射列名称:

SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables("items INNER JOIN users ON users._id=items.user_id"); 
Map<String, String> columnMap = new HashMap<String, String>();
columnMap.put("item_id", "items._id");
columnMap.put("user_id", "items.user_id");
columnMap.put("user_online", "users.online");
columnMap.put("item_name", "items.name");
queryBuilder.setProjectionMap(columnMap);

但是,当我执行以下查询时,要查找在线用户拥有的所有项目:

String[] projection = {"item_name"};
String selection = "user_online=1";
Cursor cursor = getContentResolver().query(uri, projection, selection, null, null);

我得到以下异常:

android.database.sqlite.SQLiteException: no such column: user_online (code 1): , while compiling: SELECT items.name FROM items INNER JOIN users ON users._id=items.user_id WHERE (user_online=1)

问题似乎是 setProjectionMap() 影响 projection,但不影响 selection

除了对投影执行字符串操作以手动映射列名称之外,还有其他方法可以解决此问题吗?

需要

setProjectionMap 只是因为它允许查询的 output 列名称。

您在选择中所做的操作在生成的游标中不可见,并且在任何情况下 SQLiteQueryBuilder 都不够智能,无法解析 SQL 并替换正确的列名。

只使用原来的列名:

String selection = "users.online=1";

要使列别名在选择中可用,请为您的联接创建一个视图:

CREATE VIEW user_items AS
SELECT items._id AS item_id,
       items.user_id AS user_id,
       users.online AS user_online,
       items.name AS item_name
FROM items INNER JOIN users ON users._id=items.user_id;