如何搜索共享外键的两个表(我想我问的是对的....)?

How to search two tables sharing a foreign key (I think I'm asking this right....)?

狗实体

@Entity(tableName = "dog_table")
public class DogEntity {

  private int mId;
  private String mName, mBreed;
  etc..
}

玩具实体

@Entity(tableName = "toy_table")
public class ToyEntity {

  private int mId;
  private String mName, mBrand;
  etc..
}

DogAndToy加入table实体

@Entity(tableName = "dog_and_toy_join_table",
    primaryKeys = {"mDogID", "mToyId"},
    foreignKeys = {
        @ForeignKey(
            entity = DogEntity.class,
            parentColumns = "mId",
            childColumns = "mDogID",
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        ),
        @ForeignKey(
            entity = ToyEntity.class,
            parentColumns = "mId",
            childColumns = "mToyId",
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        )
    },
    indices = {@Index("mDogID"), @Index("mToyId")}
)
public class DogAndToyJoinEntity{

  private final int mDogID, mToyId;

  public DogAndToyJoinEntity(int mDogID, int mToyId) {
    this.mDogID = mDogID;
    this.mToyId = mToyId;
  }
  etc..
}

DogAndToy 数据class

public class DogAndToy {

  @Embedded
  public Dog mDog;

  @Relation(
      parentColumn = "mId",
      entityColumn = "mId",
      entity = ToyEntity.class,
      associateBy =
      @Junction(
          value = DogAndToyJoinEntity.class,
          parentColumn = "mDogId",
          entityColumn = "mToyId"
      )
  )
  public List<ToyEntity> toyList;
}

notes:所有狗都可以有多个玩具,玩具可以与多只狗相关联。 Dog & Toy 实体不共享任何字段(例如 - Dog 没有 toyId 等)

这几天我一直在努力解决问题

how to query/get all dogs associated with one Toy (by name)

我使用 DogAndToy 数据 class 在我的 RecyclerView 中进行显示。

JOIN 和 INNER JOIN 查询让我感到困惑,我一直在尝试多种变体,但一直以零搜索结果告终。这是我最近的尝试:

  @Transaction
  @Query("SELECT dog_table.* FROM dog_table" +
      "INNER JOIN dog_and_toy_join_table ON dog_table.mId = dog_and_toy_join_table.mDogId" +
      "INNER JOIN toy_table ON toy_table.mId = dog_and_toy_join_table.mToyId " +
      "WHERE toy_table.mName LIKE :query")
  LiveData<List<DogAndToy>> findDogsByToyName(String query);

任何人都可以在 Android Room 中建议对这些查询的逐步描述吗?我在这里或互联网上任何地方找到的任何 JOIN articles/examples 都没有“加入”(外键)参考... 我是否以正确的方式尝试过?

更新澄清一下,我有 FTS tables 并且我的“基本”搜索工作正常(例如 - 按名称搜索等)

将 :toyName 替换为变量

SELECT d.mName FROM dog_table AS d
WHERE d.mId IN ( 
  SELECT j.mDogID FROM dog_and_toy_join_table AS j
  WHERE j.mToyId = (
    SELECT t.mId FROM toy_table AS t
    WHERE t.mName = :toyName));

编辑

TBH,不知道为什么它只选择一行。也许其他人可以回答。

平均时间是这样的:

select d.mName
from dog_table d 
    INNER join dog_and_toy_join_table dt
        on d.mid = dt.mDogID 
    INNER JOIN toy_table t
        ON dt.mToyId = t.mId
    WHERE t.mName = 'toy1'