用SQL连接2个表

时间:2016-09-22 08:03:54

标签: sql

我必须以特殊方式使用SQL连接2个表:

TABLE1有字段GROUP和MEMBER,TABLE2有字段GROUP和MASTER。 我必须通过将TABLE1复制到TABLE3来构建一个包含字段GROUP和ID的新TABLE3,如果TABLE1中有一个GROUP,则搜索TABLE2,如果将GROUP和MASTER复制到TABLE3。

示例:

table1

group  member
1      a
1      b
1      c
2      x
3      y

table2

group  master
3      n
3      z
1      k
9      v
2      m
7      o
8      p

预期结果,表3:

group  id
1      a       from table1
1      b       from table1
1      c       from table1
1      k       from table2
2      x       from table1
2      m       from table2
3      y       from table1
3      z       from table2
3      n       from table2

我希望一切都清楚。

那么SQL查询是什么?

谢谢,Hein

3 个答案:

答案 0 :(得分:0)

第一部分(复制成员)应该很简单:

INSERT INTO table3 (group, id) SELECT group, member FROM table1;

然后您只需复制table1中已存在的群组中的主人:

INSERT INTO table3 (group, id) SELECT group, master FROM table2 WHERE group IN (SELECT DISTINCT group FROM table1);

答案 1 :(得分:0)

试一试。当然,您需要将整个选择插入到名为Table3的新表中。

WITH TABLE1(GRP,MMBR) AS
 (SELECT 1, 'a' FROM DUAL UNION ALL
  SELECT 1, 'b' FROM DUAL UNION ALL
  SELECT 1, 'c' FROM DUAL UNION ALL
  SELECT 2, 'x' FROM DUAL UNION ALL
  SELECT 3, 'y' FROM DUAL),
TABLE2(GRP,MSTR) AS
 (SELECT 3, 'n' FROM DUAL UNION ALL
  SELECT 3, 'z' FROM DUAL UNION ALL
  SELECT 1, 'k' FROM DUAL UNION ALL
  SELECT 9, 'v' FROM DUAL UNION ALL
  SELECT 2, 'm' FROM DUAL UNION ALL
  SELECT 7, 'o' FROM DUAL UNION ALL
  SELECT 8, 'p' FROM DUAL)

SELECT * FROM (
  SELECT GRP, MMBR ID FROM TABLE1

  UNION --UNION ALL if you need duplicates

  SELECT GRP, MSTR ID FROM TABLE2
  WHERE TABLE2.GRP IN (SELECT GRP FROM TABLE1)
  )
  ORDER BY GRP, ID

答案 2 :(得分:0)

您可以在UNION ALL中使用SELECT和2个简单INSERT执行此操作,如下所示:

INSERT INTO table3(group,id) 
SELECT group,id FROM table1
UNION ALL
SELECT group,id FROM table2
SELECT * FROM table3;

如果您不想要重复值,请使用UNION代替UNION ALL来尝试:

INSERT INTO table3(group,id) 
SELECT group,id FROM table1
UNION
SELECT group,id FROM table2
SELECT * FROM table3;