MySQL 插入具有固定值和多个 select 结果的数据

MySQL insert data with fixed values and multiple select results

假设我有一个如下所示的 table 结构:

notification_table

| id | receiver_id | type | content | time |

接收者 ID 来自用户 table:

user_table

| id | username |

且内容和时间均来自广播table:

broadcast_table

| id | content | time |

所以当我需要插入这个通知table时,我需要select来自用户的id和select来自广播的内容+时间,类型固定为"system_broadcast"。我可以在一次查询中完成吗?

我试过了

INSERT INTO notification_table (receiver_id, type, content, time) 
VALUES (
       (SELECT id FROM user_table WHERE username='test' LIMIT 1), 
        'system_broadcast', 
       (SELECT content, time FROM broadcast_table)
)

但是它 returns 像 "mysql Operand should contain 1 column(s)" 这样的错误。

是的,您可以使用 insert . . . select 执行此操作。这似乎符合您最初查询的意图:

INSERT INTO notification_table (receiver_id, type, content, time) 
    SELECT (SELECT id FROM user_table WHERE username = 'test' LIMIT 1), 
           'system_broadcast',
           content, time
    FROM broadcast_table;

请注意,这将为 broadcast_table 中的每一行插入一行。您可能需要 where 子句或 limit 来仅获取特定行。