[英]Insert row in table for each id from another table
Basically I have two tables like these: 基本上我有两个这样的表:
Table 1: users 表1:用户
id_user, name, ...
Table 2: leaves 表2:叶子
id_2, employee (the column employee is the id of the user from the first table), ...
Right now the table two is empty (doesn't have rows) and for every user from the first table I want to create a row on the second one inserting the id from the first table as a value in the column employee, like: 现在表2是空的(没有行),对于第一个表中的每个用户,我想在第二个表上创建一行,将第一个表中的id作为列雇员中的值插入,如:
Table 2: leaves 表2:叶子
id employee column1 column2 column3 column4 column5
id1 1 date1 date2 integer1 integer2 string
id2 2 date1 date2 integer1 integer2 string
...
The INSERTS I tried: 我试过的INSERTS:
This one works fine: 这个工作正常:
INSERT INTO entitleddays (employee, startdate, enddate, type, days, description) VALUES (1, '2015-01-01', '2015-12-31', 3, 5, 'test');
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');
I get the following error: 我收到以下错误:
#1242 - Subquery returns more than 1 row
#1242 - 子查询返回超过1行
I do understand the error: the subquery is finding more than one result so it cannot insert the value into employee, my problem is that I don't know what syntax should I use as the noob I am. 我确实理解错误:子查询找到了多个结果,因此它无法将值插入到员工中,我的问题是我不知道我应该使用什么语法作为菜鸟我。 I just want to create a row in the second table for every row from the first table (using the id from the first table).
我只想在第二个表中为第一个表中的每一行创建一行(使用第一个表中的id)。
Just use insert . . . select
只需使用
insert . . . select
insert . . . select
insert . . . select
: insert . . . select
:
INSERT INTO entitleddays (employee, startdate, enddate, type, days, description)
SELECT id, '2015-01-01', '2015-12-31', 3, 5, 'test'
FROM users;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.