SQLite中如何连接三个表?

How to join three tables in SQLite?

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

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

Table 劳动力:id1(PK), subContractors,noOfPeople,noOfHours

Table 工作详情:id2(PK),project,workDescription,TableInfo_id(FK) //contains multiple row

Table 信息

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

Table 劳动力

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

Table 工作详情

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

假设 name 是 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;

    }

我的代码似乎无法正常工作..我该如何实现?谢谢!

  1. 为劳动力添加外键table信息中ID的指向table
  2. select * 来自 Info inner join Workforce inner join Workdetails ON Info.ID = Wordforce.SOME_FOREIGN_KEY AND Info.ID = Workdetails.TableInfo_id Where NAME = 'Paul'

认为应该可行但还没有尝试过

你需要做的第一件事是将 Table Info 的外键添加到 Table WorkForceTable WorkForce 的外键到 Table WorkDetails

然后像这样修改你的查询

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

连接三个表后根据需要修改查询。

查看添加外键的教程。