SQLite查询三个表

时间:2010-12-16 13:35:34

标签: sql android sqlite cursor

我正在开发一款Android应用,它会在列表视图中显示sqlite数据库中的一些信息。我需要一些帮助来整理我的查询。

数据库如下所示:

[monitors] 1 --- <has> --- * [results] 1 --- <has> --- * [steps]

Table monitors has columns: _id | warning_threshold | alarm_threshold | monitor_name
Table results  has columns: _id | monitor_id        | timestamp       | test_info
Table steps    has columns: _id | result_id         | correct         | response_time

我正在尝试提出一个返回的查询:
1)所有行和监视器表中的列。
2)结果表中每个监视器的最新test_info 3)从步骤表中计算每个结果的correct = true数。

返回的游标应如下所示:

_id | monitor_name | warning_threshold | alarm_threshold | test_info   | correct_count
1   | 'hugo'       | 1000              | 1500            | 'some info' | 7
2   | 'kurt'       | 800               | 1200            | 'info.....' | 5

我的查询:

SELECT * FROM
  (SELECT monitors._id AS _id,
  monitors.monitor_name AS monitor_name,
  monitors.warning_threshold AS warning_threshold,
  monitors.alarm_threshold AS alarm_threshold,
  results.test_info AS test_info
  FROM monitors
  LEFT JOIN results
  ON monitors._id = results.monitor_id
  ORDER BY results.timestamp ASC) AS inner
GROUP BY inner._id;

我差点搞定了。我能够从监视器和结果中获取信息,我仍然需要获取correct_count。任何有关整理此查询的帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

这是我的方法,使用左连接,子查询和相关子查询的组合:

SELECT monitors._id AS _id,
 monitors.monitor_name AS monitor_name,
 monitors.warning_threshold AS warning_threshold,
 monitors.alarm_threshold AS alarm_threshold,
 LastResults.test_info AS test_info,
 COUNT(CorrectSteps._id) AS correct_count
FROM monitors
LEFT JOIN 
 (SELECT * FROM results as r1 where timestamp =
   (SELECT Max(r2.timestamp) FROM results AS r2 WHERE r1.monitor_id=r2.monitor_id)) LastResults
ON monitors._id = LastResults.monitor_id
LEFT JOIN 
 (SELECT * FROM steps WHERE correct = 'true') CorrectSteps
ON LastResults._id = CorrectSteps.result_id
GROUP BY monitors._id;

答案 1 :(得分:1)

这样的事情应该有效。我无法测试它,但希望它至少会让你开始。请注意,此查询甚至不接近以进行优化。在午餐期间快速写出来:))

SELECT m._id,
       m.monitor_name,
       m.warning_threshold,
       m.alarm_threshold,
       (SELECT r.test_info
          FROM results r
         WHERE r.monitor_id = m._id
         ORDER BY r.timestamp ASC
         LIMIT 1) as 'test_info',
       (SELECT COUNT(_id)
          FROM steps s
         WHERE s.result_id IN (SELECT _id FROM results WHERE monitor_id = m._id)
           AND s.correct = 'true') as 'correct_count'
  FROM monitor m