2015-01-11 36 views
0

假设我有一个表结构象下面这样:MySQL的具有固定值和多个选择结果数据插入

notification_table

| id | receiver_id | type | content | time | 

接收机ID是从用户表:

user_table

| id | username | 

和内容和时间是从广播台:

broadcast_table

| id | content | time | 

所以,当我需要插入此通知表,我需要从用户和选择内容+时间选择ID来自广播,并且类型被固定为“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) 
) 

但它返回类似错误 “MySQL的操作数应包含1列(S)”。

回答

2

是的,你可以使用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; 

注意,这将在插入一行的每一行。您可能希望where子句或limit仅获取特定行。

+0

是的,它的工作原理。我确实有我可以处理自己的限制条件条款。谢谢。 – mrmoment