简体   繁体   中英

Android Room Inner Join Selects multiple rows

I am using the following query in Android Room to obtain values from two tables related by the foreign key. Item is the foreign key of Transaction related by column upc . unique_id is a unique transaction number.

 @Query("SELECT * FROM Transaction t INNER JOIN Item i ON i.upc=t.item_upc WHERE t.unique_id=:uniqueId")
    LiveData<List<TransactionItem>> getTransactionItemsByUID(@NonNull final String uniqueId);

When I run this command with unique transaction id, the query selects all the rows in Transactions where the upc are the same regardless of the WHERE clause. Basically, transactions with different unique_id are selected. However, I am only interested in row with exact match to the unique_id .

The TransactionItem class is defined as follows.

// TransactionItem Model

@Embedded
public ItemModel itemModel;

@Relation(parentColumn = "upc", entityColumn = "item_upc", entity = Transaction.class)
public List<Transaction> transactions;

I have spent two days googling and reading but still couldn't find the right solution. What am I overlooking here?

You telling to get Transaction and Item by INNER JOIN and then to get TransactionItem list for Item got by Transaction by @Relation JOIN, no WHERE.

You want get Transaction and Item not Transaction Item list, so TransactionItem not correct way. You want @Embedded Transaction and @Relation with ItemModel like

@Embedded
public Transaction transaction;
@Relation(parentColumn = "item_upc", entityColumn = "upc", entity = ItemModel.class)
public ItemModel itemModel; 

Guessing 1 Item needed only. Can do public List<Item> itemModels if wanted.

You use

@Transaction
@Query("SELECT * FROM Transaction WHERE unique_id=:uniqueId")
LiveData<List<TransactionItem>> getTransactionItemsByUID(@NonNull final String uniqueId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM