从两个表中选择,如果不存在则插入一个表

时间:2016-10-07 11:51:01

标签: mysql sql

我有三张桌子:

Members
 - Person_id
Sites
 - Site_id
Member_multi_site
 - Person_id
 - Site_id

我想要做的是在Person_id表中不存在同一行时将Site_idMember_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

2 个答案:

答案 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>