Oli*_*ons 3 postgresql many-to-many common-table-expression sql-insert sql-returning
我已经阅读了this、this和this,但我无法使这个 SQL 工作:
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);
Run Code Online (Sandbox Code Playgroud)
我得到:
错误:表 t1 的 FROM 子句缺少条目
我错过了什么?
尝试这个:
INSERT INTO main_phrase (phrase_id, groupe_categories_id)
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'
)
select t1.id, t2.id
from t1,t2;
Run Code Online (Sandbox Code Playgroud)
main_phrase
到main_groupecategories
具有相同description
.main_phrase.id
是一serial
列。你可以不参考任何表(包括CTE)在一个独立的VALUES
表达,你将不得不使用SELECT
一个FROM
子句。但是有一个更好的解决方案。见下文。
改用数据修改 CTE使整个操作更短、更安全、更快:
WITH p AS (
INSERT INTO main_phrase (description)
VALUES ('Mot commun féminin pluriel animaux') -- provide description once
RETURNING id, description -- and reuse it further down
)
INSERT INTO main_phrasegroupecategories (phrase_id, groupe_categories_id)
SELECT p.id, g.id
FROM p
JOIN main_groupecategories g USING (description);
Run Code Online (Sandbox Code Playgroud)
如果要使用新行的任何值,请立即将它们与另一个RETURNING
子句一起返回到第二个INSERT
.
为什么description
在(假定的)多对多关系的两个表中冗余地相同?可能是您的数据库设计中的问题。
有关的:
归档时间: |
|
查看次数: |
6940 次 |
最近记录: |