I've already read this, this and this, but I cant make this SQL work:
INSERT INTO main_phrase (description) VALUES ('Mot commun féminin pluriel animaux');
/* ERROR: */
WITH
t1 AS (
SELECT id
FROM main_phrase
WHERE description='Mot commun féminin pluriel animaux'
),
t2 AS (
SELECT id
FROM main_groupecategories
WHERE description='Mot commun féminin pluriel animaux'
)
INSERT
INTO main_phrasegroupecategories (phrase_id, groupe_categories_id)
VALUES (t1.id, t2.id);
I get:
ERROR: missing entry for the clause FROM for table t1
What am I missing?
Assumptions
main_phrase
to the row(s) inmain_groupecategories
with the samedescription
.main_phrase.id
is aserial
column.Explanation for Error
You cannot refer to any tables (including CTE) in a free-standing
VALUES
expression, you would have to useSELECT
with aFROM
clause. But there is a better solution. See below.Better Query
Use a data-modifying CTE instead to make the whole operation shorter, safer and faster:
If you want to use any values of the new rows, have them returned immediately with another
RETURNING
clause to the secondINSERT
.Why would you have the same
description
redundantly in both tables of your (presumed) many-to-many relationship? Might be a problem in your database design.Related:
Try this: