Inserting and querying data from table with foreig

2019-08-25 10:38发布

I wanted to create two related tables. My query that is creating tables looks like this:

static final String SQL_CREATE_TABLE_LISTS = 
"CREATE TABLE Lists(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);";
static final String SQL_CREATE_TABLE_ITEMS = 
"CREATE TABLE Items(IdList INTEGER, ItemName TEXT, FOREIGN KEY(IdList) REFERENCES Lists(Id));";

I want now insert and select some data from table Items, but I do not know how the query should looks like. Lets say I have one record in table Lists: id=1 and name=element1. And now I want to add 3 records to table Items, so IdList will be 1, and name will be item1, item2 and item3. How the inserting query will be like? And then, if I want to take for ex. all Names from table Items that its IdList is 1, how the select query will be like? Thanks.

1条回答
不美不萌又怎样
2楼-- · 2019-08-25 11:31

A FOREIGN KEY is a Constraint (Rule that MUST be followed), it does not define a relationshop/link for extracting data. In other words it is saying if the rule is not met then a row cannot be inserted. It is not saying every time you access either of the tables that they are automatically linked.

When inserting you you would insert the Lists first, you would then insert the Items using(checking) the available Lists. You cannot insert into/across multiple tables directly.

You need to use JOIN when querying the data as FOREIGN KEY is just a rule (constraint) that is checked when inserting a row.

So you would do something along the line of:-

SELECT Lists.Id, Lists.Name, Items.ItemName FROM Lists JOIN Items ON Lists.Id = Items.IdList

查看更多
登录 后发表回答