Search code examples
sqlsqlitewith-statement

Inserting multiple foreign keys with aliases


I'm trying to insert identities to foreign keys. Here's my code:

WITH p AS (SELECT id FROM tbl_place WHERE txt_place = "Place 1")
INSERT INTO tbl_sheet(txt_rep_no, txt_song_name, id_place, id_source_by, id_compiled_by, id_notation_by, id_type, blob_sheet1)
VALUES("1", "Song Name 1", p.id, 1, 1, 1, "", "")

This gives me error

No such column p.id

How can I select and insert to multiple foreign keys?

Edit: I tried adding "with" sentences but got error: "WITH": syntax error

INSERT INTO tbl_sheet(txt_rep_no, txt_song_name, id_place, id_source_by, id_compiled_by, id_notation_by, id_type, blob_sheet1)
WITH p AS (SELECT id FROM tbl_place WHERE txt_place = "Place 1")
WITH s AS (SELECT id FROM tbl_person WHERE txt_person = "Person 1")
WITH c AS (SELECT id FROM tbl_person WHERE txt_person = "Person 1")
WITH n AS (SELECT id FROM tbl_person WHERE txt_person = "Person 1")
SELECT "1", "Song 1", p.id, s.id, c.id, n.id, 1, ""
FROM p

Solution

  • That because you're using it in the wrong order:

    INSERT INTO tbl_sheet(txt_rep_no, txt_song_name, id_place, id_source_by, id_compiled_by, id_notation_by, id_type, blob_sheet1)
    WITH p AS (SELECT id FROM tbl_place WHERE txt_place = "Place 1")
    SELECT "1", "Song Name 1", p.id, 1, 1, 1, "", ""
    FROM p
    
    1. INSERT INTO
    2. WITH clause
    3. SELECT from table(-s) from the WITH clause