【问题标题】:Insert into 2 tables with single SQL statement instead of loop使用单个 SQL 语句而不是循环插入 2 个表
【发布时间】:2021-10-16 22:05:57
【问题描述】:

我必须在几个表的来源中插入数据,这些表本身来自 csv (COPY)。

在我在函数中使用LOOP 输入数据之前。为了可维护性和速度,我想简化这件事。

我需要将数据插入到描述表中,该表既是标题又是描述(以及多语言)。

以前我的代码如下(从循环中提取):

insert into description (label, lang_id, poi_id,date_dernier_update, date_enregistrementbdd, date_derniere_lecture) values (label, lang_id, poi_id, now(), now(), now()) RETURNING id INTO _retour_id_titre;
insert into poi_titre_poi (poi_id, titre_poi_id, titre_poi_key) values (poi_id, _retour_id_titre, label_lang);

但现在我不能:

with rows as (
insert into description (label, lang_id, poi_id)
select rdfslabelfrs, '1',  (select id from poi where uri_id = csv_poi_rdf_fr.poi) as toto from csv_poi_rdf_fr  RETURNING id 
    )
    insert into poi_titre_poi (poi_id, titre_poi_id, titre_poi_key) 
     select description.poi_id,  id , 'fr'
    FROM description;

事实上,我无法在“poi_titre_poi”表中插入“poi_id”,该表对应于在描述表中插入的那个。

我收到此错误消息:

ERROR:  more than one row returned by a subquery used as an expression
État SQL : 21000

我可以完成这项工作,还是需要循环?

【问题讨论】:

    标签: sql postgresql insert common-table-expression


    【解决方案1】:

    用假设填充缺失的位,它可以像这样工作:

    WITH description_insert AS (
       INSERT INTO description
             (label         , lang_id, poi_id)
       SELECT c.rdfslabelfrs, 1      , p.id
       FROM   csv_poi_rdf_fr c
       JOIN   poi p ON p.uri_id = c.poi
       RETURNING poi_id, id
       )
    INSERT INTO poi_titre_poi (poi_id, titre_poi_id, titre_poi_key)
    SELECT d.poi_id,  d.id , 'fr'
    FROM   description_insert d;
    

    相关:

    【讨论】:

    • 除非我弄错了,否则只有在存在某个键的概念时,连接才有效,对吧?
    • @Camel4488:连接操作不依赖于键列。连接条件(和其他 WHERE 条件)定义了连接的内容。
    • olala 我认为连接取决于键!您刚刚为我节省了数英里的代码行,非常感谢!
    • @Camel4488:当然,如果您在唯一列(“键”列)上连接,则连接不能乘以行。你甚至可以使用无条件的CROSS JOIN ...
    • 我进行了一次培训,我的培训师告诉我们内部连接和所有其他您需要的关键概念。所以我从来没有想过在不把钥匙放在我的桌子上的情况下尝试加入....(在 mysql 上很短之后,我不知道它是否在 mysql 上是强制性的)。简短的道德我应该尝试...非常感谢!
    猜你喜欢
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多