【发布时间】:2012-02-22 03:42:47
【问题描述】:
我有一个复杂的 SQLite 查询,旨在从 3 个相关表中获取总数。
以下是我的表格示例:
----
cities
----
id, name
----
surveys
----
id, cities_id
----
population
----
id, survey_id
我需要找出每个城市的调查总人数。
这是我一直在使用 c# 的方法,但我相信应该有一种更直接的方法来通过 SQLite 做到这一点。另外,我的大脑并没有使用 c# 解决我的最后一步。
//get a list of all cities
List<string> cities = new List<string>();
cmd.CommandText = "SELECT * from cities ";
cmd.ExecuteScalar();
SqlCeDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
list_cities.Add(myReader["id"].ToString().Trim());
}
//get survey ids related to these citities
List<list_key_val> list_survey_ids = new List<list_key_val>();
foreach (String city_id in cities)
{
cmd.CommandText = "SELECT * from surveys WHERE city_id = '" + city_id + "'";
cmd.ExecuteScalar();
SqlCeDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
list_survey_ids.Add(new list_key_val()
{
key = city_id,
val = myReader["id"].ToString().Trim()
});
}
}
//find total surveyed person count for each survey id.
List<list_key_val> list_surveyed_total = new List<list_key_val>();
foreach (String survey_id in list_survey_ids)
{
cmd.CommandText = "SELECT COUNT(*) from population WHERE survey_id = '" + survey_id + "'";
cmd.ExecuteScalar();
list_surveyed_total.Add(new list_key_val()
{
key = survey_id,
val = count = (int)cmd.ExecuteScalar();
}
}
//find surveyed count as city id -> survey id -> surveyed count
List<list_key_val> list_city_surveyed_total = new List<list_key_val>();
foreach (String city_id in list_cities)
{
//dar... complex nested key calculations here, possibly?
}
我了解 SQLite 在组合查询方面存在一些限制。感谢您的所有帮助!
【问题讨论】: