使用GROUP BY和CursorLoader - Android

时间:2014-01-09 08:14:20

标签: android sqlite group-by android-cursorloader

我正试图从Contacts

获取所有ContactsContract.CommonDataKinds.Email.CONTENT_URI

使用ContactIDNameCursorLoader分组。

例如,如果联系人有2封电子邮件,我将只收到有关此联系人的一行。

基本上,它应该是这样的:

SELECT ContactID, Name
FROM Table
GROUP BY ContactID, Name

我的代码:

String filter = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE '')) 
GROUP BY ((" + ContactsContract.CommonDataKinds.Email.CONTACT_ID + ", display_name";

final static String[] PROJECTION =
{
   Utils.hasHoneycomb() ? Contacts.DISPLAY_NAME_PRIMARY : Contacts.DISPLAY_NAME,
   ContactsContract.CommonDataKinds.Email.CONTACT_ID,
};

return new CursorLoader(getActivity(),
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    ContactsQuery.PROJECTION,
                    filter,
                    null,
                    ContactsQuery.SORT_ORDER);

我收到了下一个SQLite错误:

"Caused by: android.database.sqlite.SQLiteException: near ",": syntax error: , while compiling: SELECT DISTINCT display_name, contact_id FROM view_data_restricted data WHERE (1 AND mimetype_id = 1) AND ((data1 NOT LIKE '')) GROUP BY ((contact_id, display_name)) ORDER BY sort_key"

所以这是我的问题:

SELECT DISTINCT display_name, contact_id FROM view_data_restricted data 
WHERE (1 AND mimetype_id = 1) AND ((data1 NOT LIKE '')) 
GROUP BY ((contact_id, display_name)) ORDER BY sort_key
  1. “DISTINCT”由cursorLoader添加。为什么?
  2. 我知道有多个"(" / ")"标志,这是我发现处理添加“GROUP_BY”的最佳方式。任何其他想法都会有所帮助。
  3. 我在","附近找不到错误所说的问题。

2 个答案:

答案 0 :(得分:1)

问题在于CursorLoader如何构造您的查询语句。

根据this

  

GROUP BY子句必须遵循WHERE子句中的条件   必须在ORDER BY子句之前使用。

不幸的是,如果您将Selection,Projection和SortOrder作为参数传递,则无法实现此目的。 “Group By”声明中没有“破解”的地方..

答案 1 :(得分:-1)

select (SELECT  group_concat(DISTINCT display_name) FROM view_data_restricted) as a,(SELECT  group_concat(DISTINCT contact_id) FROM view_data_restricted) as b FROM view_data_restricted data 
WHERE (1 AND mimetype_id = 1) AND ((data1 NOT LIKE '')) 
GROUP BY ((contact_id, display_name)) ORDER BY sort_key

分散多列:

请参阅此链接:

reference link