android和ios sqlite 多表查询
2017-03-25 本文已影响445人
Flynn_X
我相信开发Android和ios的同事都知道这两个系统用的是同一套数据库sqlite,他们的数据库操作方法都是相同的。
在很多时候,android、ios 也有多表查询的情况,比如省市级的查询。
后台同事有的时候并不清楚省市级该怎么给到前端同事。
当然解决的方法有很多,比如写本地数据库sqlite,或者文件本地存储等等多种方式。
移动端(android、ios)当然是希望后台同事能给一个接口进行查询,这是最好的解决方法,但是当必须写到本地后,省市级就是分开的不同表,移动端想要通过一个县(区)名查出省市,就涉及到多表查询了。
那如何进行多表查询呢?下面我用一个示例说明。
表1:province(省)

表2:city(市)

表3:county(县、区)

- 上面有三张表provice、city、county 分别对应的省市区。
- 先进行通过county_id查询 出县名和市名。
查询语句如下:
“select *from county inner join city on county.city_id = city.city_id where county.county_id = ?”
这样句可以查出city、county 中所有数据。
Android中通过Cursor就可以获取两张表中所有数据。
- 下面通过county_id 查询出三张表的数据。
查询语句如下:
“select *from county inner join city on county.city_id = city.city_id inner join province on province.province.id = city.province_id where county.county_id = ?”
这样就可以查出三张表的内容。
更多表联合查询以此类推sql语句。
下面给出一个android 查询三张表中数据的代码示例。
public static SampleInfo qurySampleInfo(Context context,SampleInfo sampleInfo){
SampleInfo sampleInfo1 = null;
DbManager db = DbManager.getInstance(context);
SQLiteDatabase sq = db.openDatabase();
try {
//select * from sample_info inner join patient_info on sample_info.PatientID = patient_info.PatientID and sample_info.SampleID = ?;
Cursor cursor = sq.rawQuery("select * from sample_info inner join patient_info on sample_info.PatientID = patient_info.PatientID " +
"inner join doctor_info on sample_info.DoctorID = doctor_info.DoctorID where sample_info.SampleID = ?; ",new String[]{sampleInfo.SampleID+""});
while (cursor.moveToNext()) {
Log.e("多表查询",cursor.getString(cursor.getColumnIndex("realName")));
Log.e("多表查询",cursor.getString(cursor.getColumnIndex("DoctorID")));
}
}catch (Exception e){
e.printStackTrace();
}
db.closeDatabase(sq,null);
return sampleInfo;
}
demo 源码等我有时间再奉上,持续更新,欢迎大家一起探讨。