admin

如何搜索共享外键的两个表(我想我问这个正确的吗?)?

sql

Dog entity

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

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

Toy entity

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

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

DogAndToy join table entity

@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数据类

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;
}

注意:所有的狗都可以有多个玩具,并且玩具可以与多个狗相关联。 狗与玩具实体不共享任何字段(例如-狗没有toyId等)

我已经尝试了好几天来缠住我的头

如何查询/获取与一个玩具相关的所有狗(按名称)

我将DogAndToy数据类用于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文章/示例都没有“
join”(外键)参考…我什至以正确的方式尝试了吗?

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


阅读 139

收藏
2021-07-01

共1个答案

admin

用变量替换: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'
2021-07-01