I have created the following tables in SQLite3 to tag items (after reading this great response). The tags are saved in the table Tags and the ItemTags will show the relation between one item (from the table Items) and one or more tags (from the table Tags).
CREATE TABLE Items ItemID INTEGER PRIMARY KEY, Title TEXT, Comment TEXT;
CREATE TABLE Tags TagID INTEGER PRIMARY KEY, Title TEXT;
CREATE TABLE ItemsTags ItemID INTEGER, TagID INTEGER;
When submitting a new row, the user will enter a title and a comment (which will be saved in the table Items) and chose from one or more tags (which are chosen/added from/to the table Tags). So far, I’ve for instance managed to do this:
INSERT INTO Items (Title, Comment) VALUES ('First title', 'First comment');
I want the column ItemID to be a INTEGER PRIMARY KEY, but at the same time, I want to access that value in the same call. Say, for instance, that my table Tags has the following layout:
TagID | Title
------|----------
1 | First tag
2 | Second tag
and that I want to tag the above mentioned statement (“First title”, which has the TitleID 1) with TagID 1 and 2, and save the relation to the table ItemsTags. After I’m done, I want the following changes to be made:
Table: Items
TitleID | Title | Comment
--------|-------------|--------------
1 | First title | First comment
Table: Tags
TagID | Title
------|----------
1 | First tag
2 | Second tag
Table: ItemsTags
TagID | ItemID
------|---------
1 | 1
2 | 1
How can I achieve this? Thanks in advance!
You cannot insert rows into two separate tables with a single call to the database, nor can you insert two rows into the same table with a single call. You will need four in this case:
If you place them all inside a transaction, they will all get committed at the same time, with only a single lock placed on the database file.