如何创建具有空值的两个表的并集?

时间:2014-08-19 00:25:51

标签: mysql join union

我有两个MySQL表," ucharacters"和#34; uplaces,"两者都有列" ucharacter。"两个表中的ucharacter列之间存在一些重叠,但某些值对于每个表都是唯一的。每个表格还包含" episode"和"线,"但是" uplaces"表也​​有一个"地方"柱。这将创建此架构的简单版本:

CREATE TABLE ucharacters (
  ucharacter VARCHAR(50),
  episode INT(2),
  line INT(6)
  );

CREATE TABLE uplaces (
  ucharacter VARCHAR(50),
  episode INT(2),
  line INT(6),
  place VARCHAR(40)
  );

INSERT INTO ucharacters VALUES ('Molly', 4, 123);
INSERT INTO ucharacters VALUES ('Leo', 5, 567);
INSERT INTO uplaces VALUES ('Leo', 5, NULL, 'Athens');

我想从组合这些的临时表中进行选择,以便它保留每个表中的每一行,并根据需要使用NULL值。结果如下:

UCHARACTER  EPISODE LINE PLACE
Molly       4       123  NULL
Leo         5       567  NULL
Leo         7       NULL Athens

现在是我的代码:

SELECT tabkey.ucharacter, 

ucharacters.episode, ucharacters.line, 

uplaces.episode, uplaces.line, uplaces.place

FROM 

(SELECT ucharacters.ucharacter FROM ucharacters
 UNION ALL
 SELECT uplaces.ucharacter FROM uplaces) as tabkey

LEFT JOIN

ucharacters on tabkey.ucharacter = ucharacters.ucharacter

LEFT JOIN

uplaces on tabkey.ucharacter = uplaces.ucharacter;

这适用于第一行(Molly,4,123,NULL),但随后给出两个相同的(Leo,5,567,Athens)行,将两个表组合在一起。我怎样才能获得上面输入的结果呢?

http://sqlfiddle.com/#!2/a7013e/1

谢谢!

1 个答案:

答案 0 :(得分:2)

  

我想从组合这些的临时表中进行选择,以便保留每一行>从每个表中,适当地使用NULL值。结果如下:

如果这就是你想做的全部,你能不能简单地使用下面的查询?

SELECT ucharacter, episode, line, null FROM ucharacters
UNION ALL
SELECT ucharacter, episode, line, place FROM uplaces;

http://sqlfiddle.com/#!2/a7013e/17/0