如何从android中的sqlite中的两个表中获取数据

时间:2014-04-04 05:47:03

标签: android sql sqlite

我无法使用左连接从android中的两个表中获取数据。

这是我的疑问:

public Cursor getrespondentDataNew(String loc_id) {
        Cursor cur = null;

final String MY_QUERY = "SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r INNER JOIN respondentType rt ON r.type_code = rt.rtype_code WHERE r.site_code='" + loc_id + "'";

        cur = db.rawQuery(MY_QUERY, null);
 Log.i("sql:", "SQL Test=" + MY_QUERY);
 Log.i("cur:", "cur Test=" + cur.getCount());

final String MY_QUERY = "SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r INNER JOIN respondentType rt ON r.type_code = rt.rtype_code WHERE r.site_code=?";
cur = db.rawQuery(MY_QUERY, new String[]{loc_id});

...

04-04 11:45:28.212: I/sql:(11017): SQL Test=SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r,respondentType rt where r.type_code = rt.rtype_code and r.site_code='4'
04-04 11:45:28.224: I/cur:(11017): cur Test=0

编辑:如果我运行此查询:为什么我获取rt.rtype_name的最后一个值:

SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r,respondentType rt where r.type_code = rt.rtype_code   or r.site_code='4' group by  r.code

在这两种情况下我都没有得到价值,这个查询有什么问题。

我的桌子:

respondentTable enter image description here

respondentType

enter image description here

我正在测试site_code 4。

2 个答案:

答案 0 :(得分:1)

您可以按照查询样式

以其他方式尝试
final String MY_QUERY = "SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r,respondentType rt where r.type_code = rt.rtype_code and r.site_code='" + loc_id + "'";

答案 1 :(得分:0)

我使用左外连接解决问题。

SELECT r.name, r.site_name, r.age, r.gender, rt.rtype_name, r.parent_code, r.code, r.site_code, r.interview_date FROM respondentTable r LEFT OUTER JOIN respondentType rt ON r.type_code = rt.rtype_code    where r.site_code='4'