从另一个表中每个id插入一行到表中

3
基本上我有两个像这样的表:
表1:用户

Table 2: user_details

表2:用户详情
id_user, name, ...
表2:叶子
id_2, employee (the column employee is the id of the user from the first table), ...

目前表2为空(没有行),我想为第一个表中的每个用户在第二个表中创建一行,将第一个表中的ID作为值插入到员工列中,如下所示:

表2:请假

id    employee    column1    column2    column3    column4    column5   
id1   1           date1      date2      integer1   integer2   string
id2   2           date1      date2      integer1   integer2   string
...

我尝试过的插入语句如下:
  1. This one works fine:

    INSERT INTO entitleddays (employee, startdate, enddate, type, days, description)
    VALUES (1, '2015-01-01', '2015-12-31', 3, 5, 'test');
    
  2. Here I tried what I explained above, but it doesn't work:

    INSERT INTO entitleddays (employee, startdate, enddate, type, days, description)
    VALUES ((SELECT id from users), '2015-01-01', '2015-12-31', 3, 5, 'test');
    

我收到了以下错误:

#1242 - 子查询返回多行

我了解这个错误:子查询找到了多个结果,因此无法将值插入到employee中。我的问题在于,作为一个菜鸟,我不知道应该使用什么语法。我只想为第一个表中的每一行创建第二个表中的一行(使用来自第一个表的id)。

1个回答

17

只需使用 insert . . . select

INSERT INTO entitleddays (employee, startdate, enddate, type, days, description)
    SELECT id, '2015-01-01', '2015-12-31', 3, 5, 'test'
    FROM users;

2
新手,FYI,子查询 (SELECT id from users) 返回多行,而 VALUE() 部分应该只有一行。因此,您创建的语句对于 VALUES() 的第一列具有多个值,这不是有效的 SQL。 - user151841
就是这么简单...谢谢! - Noob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接