我正在创建一个应用程序作为学习工具,但在连接查询方面遇到困难。
我有一个数据库,其中包含两个表 - horses 和 covers - 声明如下;
private static final String HORSES_CREATE = "create table horses (_id integer primary key autoincrement, "
+ "name text not null, type integer not null, birthDate text not null, vaccineDate text not null, "
+ "inFoal integer not null, notes text not null);";
“类型”字段指的是种马、母马、阉马等,它是从微调器中选择的(从 XML 字符串数组填充)。
private static final String COVERS_CREATE = "create table covers (_id integer primary key autoincrement, "
+ "stallionName integer not null, mareName integer not null, firstCoverDate text not null, lastCoverDate text not null, "
+ "scan14Date text not null, scan28Date text not null, foalingDate text not null, inFoal integer not null, notes text not null);";
stallionName 实际上存储为马表中马的 _id 字段。它是从一个微调器中选择的,该微调器仅显示在马匹表中类型定义为“Stallion”的马匹。 (同样适用于 Mare)。
我有一个类“DatabaseHelper”来创建和升级表,每个表都有自己的适配器类“horsesDbAdapter”和“coversDbAdapter”,其中包含添加、编辑和删除条目以及相关查询的方法。 (fetchAllHorses(), fetchHorse(long rowId) )
例如:
public Cursor fetchAllHorses() {
return mDb.query(DATABASE_TABLE,
new String[] { KEY_ROWID, KEY_NAME, KEY_TYPE, KEY_BIRTHDATE,
KEY_VACCINEDATE, KEY_INFOAL, KEY_NOTES }, null, null,
null, null, null);
}
(全部改编自Android记事本示例)
我在 ListView 中显示了 covers 表的内容(仅显示 stallionName 和 mareName)。但由于这些字段仅包含对 horses 表的唯一引用,所有显示的都是相当无信息的 _id 字段。
我的问题是;我怎样才能让马匹的相关名称显示在 listView 中?我已经阅读了有关连接查询等的内容,但是当我尝试实现它们时却迷路了。我假设我必须加入 horses._id 和 covers.stallionName(然后为 MareName 制作一个几乎相同的人),但我找不到如何执行此操作的具体示例。
如果需要任何其他信息/代码,请告诉我。
如有任何帮助,我们将不胜感激,在此先感谢您。
编辑: 我已经在 horses 表中创建了引用 (_id) 的 stallionName 和 mareName 外键,但我仍然不确定如何以及在何处实现连接查询;它应该在 horsesDbAdapter、coversDbAdapter 还是 coversList 类中? (coversList 是创建和填充 listView 的类) 封面表声明现在显示为;
private static final String COVERS_CREATE = "create table covers (_id integer primary key autoincrement, "
+ "stallionName integer not null, mareName integer not null, firstCoverDate text not null, lastCoverDate text not null, "
+ "scan14Date text not null, scan28Date text not null, foalingDate text not null, inFoal integer not null, notes text not null," +
"FOREIGN KEY (stallionName) REFERENCES horses (_id), FOREIGN KEY (mareName) REFERENCES horses (_id));";
最佳答案
我是 Android 和 SQLLiteHelper 的新手,并且想知道同样的事情。
看完这篇文章,我发现定义表间连接的方法是用SQLLiteQueryBuilder.setTables
方法完成的。查看reference here
我从 this blog 得到这个
希望这有助于为读者指明正确的方向。
关于Android SQLite 连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11349950/