如何在SQLite中加入三个表?

时间:2015-10-10 17:50:01

标签: java android sqlite outer-join

如何在SQLite中连接三个表?我有三个表,一个是Info,第二个是workForce,第三个是workDetails

表格信息:id(PK),name,status,date,weather

表WorkForce:id1(PK), subContractors,noOfPeople,noOfHours

表工作详细信息:id2(PK),project,workDescription,TableInfo_id(FK) //contains multiple row

表格信息

  ID          NAME        Weather        Date     Status
 ----------  ----------  ----------  ----------  ----------
    1           Paul        Sunny         15/10      MC
    2           Allen       Rainy         15/10      Working

Table WorkForce

ID1          SubContractors   NoOfPeople      NoOfHours
----------  --------------   ----------       ----------
1           AAA                2                 2
2           BBB                3                 1

表工作详情

ID2         Project       WorkDescription        TableInfo_id
----------  ----------     --------------          ----------
1              A               B                       1
2                                                      1
3                                                      1
4                                                      1
5               C               D                      2
6                                                      2
7                                                      2
8                                                      2

假设名称是Paul,因此将检索ID为1且TableInfo_id为1的所有行。

这是我到目前为止所尝试的内容

public Cursor readEntry(String name) {

        String selectQuery = ("SELECT Weather,Date,Status,SubContractors,NumberOfPeople,NumberOfHours,TimeIn,TimeOut FROM "+TABLE_INFO+TABLE_WORKFORCE+TABLE_WORKDETAILS+ "WHERE Name= ? AND"+ID=ID1+ "AND"+ID=TableInfo_id);
        Cursor c = database.query(TABLE_INFO,TABLE_WORKFORCE,TABLE_WORKDETAILS,new String[]{id,name,weather,date,status,iD1,subcontractors,numberOfPerson,numberOfHours,id2project,workDescription,TableInfo_id},MyDatabaseHelper.Name+"=?",
                new String[] { String.valueOf(name)}, null, null, null, null,null,null,null,null,null,null,null,null);

        if (c != null) {
            c.moveToFirst();
        }
        return c;

    }

我的代码似乎无法正常工作。我可以实现这一目标吗?谢谢!

2 个答案:

答案 0 :(得分:1)

您需要做的就是将 Table Info 的外键添加到 Table WorkForce 中,将 Table WorkForce 的外键添加到表工作细节

然后写这样修改您的查询

Select * from Table Info tf
LEFT JOIN Table WorkForce twf ON twf.tf_id = tf.id
LEFT JOIN Table WorkDetails twd ON twd.tw_id = twf.id

加入三个表后,根据需求修改查询。

查看添加外键的教程。

答案 1 :(得分:0)

  1. 将一个外键添加到劳动力表中,指向信息表中的ID
  2. select * from Info inner join Workforce inner join Workdetails ON Info.ID = Wordforce.SOME_FOREIGN_KEY AND Info.ID = Workdetails.TableInfo_id Where NAME =' Paul'
  3. 认为应该工作还没有尝试过