jOOQ - multi-field for insertion

ぃ、小莉子 提交于 2019-12-08 01:40:58

问题


I would like to express the following INSERT statement:

context.insertInto(TABLE A)
   .set(<FIELD A, FIELD B>, context.select(FIELD A, FIELD B).from(B).where(...))
   .set(... other field of table A ...)
   .set(... other field of table A ...)
   .set(... other field of table A ...)
   .returning()
   .fetch()

The sub-select returns one row with two columns (FIELD A and FIELD B) which need to be inserted into the target TABLE A. The reason for this is that <FIELD A, FIELD B> is the primary key of TABLE B. TABLE A is refering to TABLE B (foreign key).

Is this possible?


回答1:


I'm not sure if this is possible with any SQL dialect in the first place, via INSERT .. VALUES, but you can certainly express that sort of query using INSERT .. SELECT:

INSERT INTO a (a, b, x, y, z)
SELECT a, b, ... other value ..., ... other value ..., ... other value ...
FROM b
WHERE ...
RETURNING *;

Or with jOOQ

context.insertInto(TABLE A, ... columns ...)
       .select(
           select(
               FIELD A, 
               FIELD B,
               ... other field of table A ...,
               ... other field of table A ...,
               ... other field of table A ...)
          .from(B)
          .where(...))
       )
       .returning()
       .fetch()


来源:https://stackoverflow.com/questions/31959180/jooq-multi-field-for-insertion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!