我有三张桌子:
Members
- Person_id
Sites
- Site_id
Member_multi_site
- Person_id
- Site_id
我想要做的是在Person_id
表中不存在同一行时将Site_id
和Member_multi_site
插入Member_multi_site
表。
因此,如果在Sites
表格中有3行1
2
3
而在Members
表格中有1行1
它应该像这样将它们添加到Member_multi_site
表中:
-----------------------
| Person_id | Site_id |
-----------------------
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
我设法通过手动插入Site_id
来实现它的工作:
SET @id = 0;
INSERT INTO
Member_multi_site (
Person_id,
Site_id,
)
SELECT
Person_id,
@id,
FROM
Members
WHERE
Person_id
NOT IN (
SELECT
Person_id
FROM
Member_multi_site
WHERE
Site_id = @id
)
我无法弄清楚如何更改此查询,因此我无需手动输入Site_id
。
答案 0 :(得分:1)
如果表格不存在,您可以cross join
表格并插入行。
INSERT INTO
Member_multi_site (
Person_id,
Site_id
)
SELECT
Person_id,
Site_id
FROM
Members
CROSS JOIN Sites
WHERE Person_id NOT IN (SELECT Person_id FROM Member_multi_site)
AND Site_id NOT IN (SELECT Site_id FROM Member_multi_site)
或者您可以使用not exists
INSERT INTO
Member_multi_site (
Person_id,
Site_id
)
SELECT
Person_id,
Site_id
FROM
Members m
CROSS JOIN Sites s
WHERE NOT EXISTS (select 1 from Member_multi_site
where person_id = m.person_id and site_id = s.site_id)
答案 1 :(得分:1)
请在测试环境中检查以下SQL脚本 我希望它有所帮助
<modules>
<module>A</module>
<module>B</module>
</modules>