简体   繁体   中英

select columns from multiple tables using nested query in sqlite3

I have 3 tables - lists , items , list_items in my SQLite3 database. The table list_items is a many-to-many table comprising of following columns - list_id , item_id , quantity - where list_id is from lists table, item_id is from items table and quantity is a new field. In my application, I would like to display item names and their corresponding quantities for a given list. I am able to fetch all the items in a given list using this SQL query:

select item_name from items where item_id in (select item_id from list_items where list_id=1)

But I am not aware of how to fetch the column quantity from list_items along with the names in the above query. Can someone please help me fixing this query?

You can try below - using join

select item_name,quantity
from items i inner join list_items li on i.item_id =li.item_id 
where list_id=1

Why not do the JOIN ?

select i.item_name, li.quantity   
from items i inner join
     list_items li
     on li.item_id = i.item_id
where li.list_id = 1;

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