sqlite GROUP项BY编辑器和HAVING日期​​等于MAX

时间:2014-02-08 17:34:28

标签: android sql sqlite android-sqlite

我有2个表(见下面的模式)与一对多关系链接:

Item

id, title, date, editor_id
1, item1, 10 1
2, item2, 20, 2
3, item3, 30, 2
4, item4, 40, 5
5, item5, 50, 5
6, item6, 60, 5

Editor

id, name
1, editor1
2, editor2
3, editor3
4, editor4
5, editor5

项目 4,5和6具有相同的编辑器。现在,我想查询按editor_id分组并date = MAX (date)的所有项目,如下所示:

count, item.title, editor.name, item.date
1, item1, editor1, 10
1, item2, editor2, 20
1, item3, editor3, 30
3, item6, editor5, 60  << because 60 (date for item6) is greater than 50 and 40 which are all in editor5

这是我试过的:

String having = MySQLiteHelper.COLUMN_DATE
                + " IN (SELECT MAX(" + MySQLiteHelper.COLUMN_DATE + ") FROM "
                + MySQLiteHelper.TABLE_ITEM + ") ";
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEM, itemColumns,
                selection, null, MySQLiteHelper.COLUMN_EDITOR_ID, having,
                MySQLiteHelper.COLUMN_DATE + " DESC");

我的输出与我期待的不同:

count, item.title, editor.name, item.date
1, item1, editor1, 10
1, item2, editor2, 20
1, item3, editor3, 30
3, item4, editor5, 40 << got 40 wich is not MAX of (40, 50, 60)

希望很清楚。

感谢。

1 个答案:

答案 0 :(得分:1)

SQLite允许您拥有一个聚合查询,该查询的select中的列未聚合而不在group by子句中。 SQLite为此选择任意值:正如documentation解释:

  

对结果集中的每个非聚合表达式求值一次   任意选择的数据集行。

我的猜测是生成的查询格式为:

select count(*) as count, item.title, editor.name, item.date
. . . 
group by item.title, editor.name
. . .

返回的日期是任意。如果您想要最长日期,请选择max(item.date)代替:

select count(*) as count, item.title, editor.name, max(item.date) as "date"
. . . 
group by item.title, editor.name
. . .