Mysql 根据另一个 table 插入多条记录

Mysql insert multiple records based on another table

我有

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

对于用户中的每个 ID,我需要将 3 个默认行添加到模板 table。 示例:

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

在我的模板中 table 我应该有

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)

听起来像 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
);

如果你是第一次做,模板中没有记录table那么你可以去掉上面的where子句