Android SQLITE - 没有返回正确的数据?

时间:2014-07-03 08:05:46

标签: java android sql sqlite

我在Android中遇到SQL查询问题 - 它似乎没有返回正确的结果,我认为可能是由于我的查询结构。

这是一个正在运行的应用。我有一个正常工作的初始查询,这让我在最后三次运行中最常见,即:

Cursor workout = db.rawQuery("SELECT ActivityID, DistanceID FROM Workout WHERE _id IN(Select _id FROM Workout ORDER BY _id DESC LIMIT 3) Group By ActivityID, DistanceID HAVING COUNT(*) > 1", null);

所以现在我在最后三次跑步中有最常见的距离+活动(跑步/骑自行车等),所以我想运行一个查询,让我在最后三次与禁食的活动+距离组合时间,所以我有这个:

                Cursor fastestWorkout = db.rawQuery
                            ("Select _id, RunTimeSeconds, Distance FROM Workout WHERE ActivityID = " + workout.getInt(0) +
                            " AND DistanceID = " + workout.getInt(1) +
                            " AND RunTimeSeconds IN " +
                            "(Select Min(RunTimeSeconds) From Workout WHERE ActivityID = " + workout.getInt(0) +
                            " AND DistanceID = " + workout.getInt(1) +
                            " ORDER BY _id DESC LIMIT 3)" +
                            " ORDER BY _id DESC LIMIT 3", null);

所以这里唯一特别的是子查询让我获得最快的时间,我想这可能是错误的,但我无法解决原因。光标在结尾处有三个结果,它应该是一个(有两个活动+距离相同而且一个唯一 - 具有不同的RunTimeSeconds,所以它应该拉回那个最快的那个。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望行具有最快的运行时间。而不是使用子查询来查找此值,为什么不只是按此运行时间排序并选择第一个结果:

         Cursor fastestWorkout = db.rawQuery
                        ("Select _id, RunTimeSeconds, Distance FROM Workout WHERE ActivityID = " + workout.getInt(0) +
                        " AND DistanceID = " + workout.getInt(1) +
                        " ORDER BY RunTimeSeconds LIMIT 1", null);

答案 1 :(得分:0)

感谢您的帮助!我设法最终想到了这一个! Bwt的建议与运行时的排序是让我在那里的!

我只是使用子查询从最后三次运行中进行选择,然后我可以按运行时间排序并将其限制为只有一个结果,获得最快的运行!

        Cursor fastestWorkout = db.rawQuery
                       ("Select _id, RunTimeSeconds, DistanceID FROM (Select _id, RunTimeSeconds, DistanceID, ActivityID FROM Workout ORDER BY _id DESC LIMIT 3) WHERE ActivityID = " + workout.getInt(0) +
                        " AND DistanceID = " + workout.getInt(1) +
                        " ORDER BY RunTimeSeconds LIMIT 1", null);

感谢您的帮助和答案!