kcc__
kcc__

Reputation: 1648

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?

Upvotes: 0

Views: 219

Answers (1)

user12734636
user12734636

Reputation:

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

Upvotes: 1

Related Questions