Mysql根据另一个表插入多个记录

时间:2017-02-08 02:32:29

标签: mysql sql

我有

Table User with fields: Id, Name
Table Template with fields: Id, DefaultField, user_id

对于User中的每个Id,我需要向Template表添加3个默认行。 例如:

User Table has:
1   |  "John Doe"
2   |  "Alan Smith"

在我的模板表中,我应该

1  | "Name" | 1
2  | "Email" | 1
3  | "Contact Number" | 1
4  | "Name" | 2
5  | "Email" | 2
6  | "Contact Number" | 2

我希望如下所示,但如果执行第一个查询,第二个查询将无效

INSERT INTO template (name, user_id)
SELECT 'Name', id
FROM user
WHERE id NOT IN (SELECT DISTINCT user_id FROM template)

INSERT INTO template (name, user_id)
SELECT 'Email', id
FROM user
WHERE id NOT IN (SELECT DISTINCT user_id FROM template)

INSERT INTO template (name, user_id)
SELECT 'Contact Number', id
FROM user
WHERE id NOT IN (SELECT DISTINCT user_id FROM template)

1 个答案:

答案 0 :(得分:1)

听起来像CROSS JOIN应该这样做。

insert into template (name, user_id)
select t.name, u.id
from user u cross join (
    select 'Name' name union all
    select 'Email' name union all
    select 'Contact Number' name
) t where not exists (
    select 1
    from template z
    where u.id = z.user_id
);

如果你是第一次这样做,并且模板表中没有记录,那么你可以摆脱上面的where子句。