如何将 select 查询的结果作为属性值插入到插入语句中

How to have the result of a select query being inserted as a value of an attribute in an insert statement

如标题所述,我试图在插入语句中插入一个 select 查询的结果,代码是:

INSERT INTO entry (
        event_id,
        entry_no, 
        entry_starttime, 
        entry_finishtime,
        comp_no,
        team_id,
        char_id
    ) VALUES ( 
        **SELECT event_id FROM event WHERE carn_date = to_date((SELECT carn_date FROM carnival WHERE carn_name = 'RM Autumn Series Caulfield 2022'), 'DD/MM/YYYY') and eventtype_code = '21K',**
        1,
        TO_DATE('08:31:44', 'HH24:MI:SS'),
        TO_DATE('09:02:44', 'HH24:MI:SS'),
        6,
        NULL, 
        NULL
    );

我试图将 SELECT event_id FROM event WHERE carn_date = to_date((SELECT carn_date FROM carnival WHERE carn_name = 'RM Autumn Series Caulfield 2022'), 'DD/MM/YYYY') and eventtype_code = '21K' 的结果作为 event_id 的值插入,但它给我的语法错误是 'missing expression'.

但是当我 运行 单独 select 语句时,它完美地给出了期望的结果。即 14.

预先感谢您的帮助。

您可以使用 INSERT ... SELECT:

INSERT INTO entry (
  event_id,
  entry_no, 
  entry_starttime, 
  entry_finishtime,
  comp_no,
  team_id,
  char_id
)
SELECT event_id,
       1,
       TRUNC(carn_date) + INTERVAL '08:31:44' HOUR TO SECOND,
       TRUNC(carn_date) + INTERVAL '09:02:44' HOUR TO SECOND,
       6,
       NULL,
       NULL
FROM   event
WHERE  eventtype_code = '21K'
AND    carn_date = (SELECT carn_date
                    FROM   carnival
                    WHERE carn_name = 'RM Autumn Series Caulfield 2022');

您还可以将嵌套的 SELECT 包裹在 () 括号中;然而,当您可能不想要时,您将获得 entry_starttimeentry_finishtime 列的年、月和日的默认日期组件(这将是当前月份和年份的第一天)而是希望它们与狂欢节的日期相匹配(第一个查询所做的)。

INSERT INTO entry (
  event_id,
  entry_no, 
  entry_starttime, 
  entry_finishtime,
  comp_no,
  team_id,
  char_id
) VALUES ( 
  ( SELECT event_id
    FROM   event
    WHERE  carn_date = ( SELECT carn_date
                         FROM   carnival
                         WHERE  carn_name = 'RM Autumn Series Caulfield 2022')
    AND    eventtype_code = '21K' ),
  1,
  TO_DATE('08:31:44', 'HH24:MI:SS'),
  TO_DATE('09:02:44', 'HH24:MI:SS'),
  6,
  NULL, 
  NULL
);

注意:切勿在已经是 DATE 的值上使用 TO_DATE。如果您想将 DATE 的时间部分截断回午夜,那么请使用 TRUNC 函数,而不是依赖于隐式转换为字符串然后返回日期。

db<>fiddle here