MySQL中的嵌套联合声明

时间:2013-08-27 09:51:12

标签: mysql select insert union

我有3个表,想从2个表中获取数据并将其转储到第三个表。这两个表也可以具有互连数据和独立数据。所以,我希望得到所有3种可能场景的结合。

3个不同的表是a,b和c

示例查询:

Insert into c (scode, cname, fvalue, ISIN, nsymbol, paidup)

select scode, cname, fvalue, ISIN, null, null from a,b where a.ISIN <> b.ISIN

union

select scode, cname, fvalue, ISIN, nsymbol, paidup from a,b where a.ISIN = b.ISIN

union

select null, b.cname, b.fvalue, b.ISIN, b.nsymbol, b.paidup from a, b where b.ISIN <> a.ISIN

我为每条记录插入了3行,其中我只想插入1条记录。任何帮助将不胜感激。

我正在寻找类似下面的内容

表A

scode cname fvalue ISIN

FB,Facebook,10,INAB13230LL IBM,International Business Machines,10,INAB13230AB

表B

nsymbol cname fvalue ISIN payup

FBOOK,Facebook,10 INAB13230LL,10 MSFT,Microsoft,10,INAB13230MS,10

表C

scode cname fvalue ISIN nsymbol paidup

FB,Facebook,10,INAB13230LL,FBOOK,10 IBM,International Business Machines,10,INAB13230AB,NULL,NULL Null,Microsoft,10,INAB13230MS,MSFT,10

提前致谢。

1 个答案:

答案 0 :(得分:1)

也许这样的事情会有所帮助。我会尽量用点符号指定表格列,以确定事物的来源,我会使用排除JOIN,如下所示:

select a.scode, a.cname, a.fvalue, a.ISIN, null, null from a left join b on a.ISIN = b.ISIN where b.ISIN IS NULL

union

select a.scode, a.cname, a.fvalue, a.ISIN, a.nsymbol, a.paidup from a inner join b on a.ISID = b.ISID

union

select null, b.cname, b.fvalue, b.ISIN, b.nsymbol, b.paidup from b left join a on b.ISIN = a.ISIN where a.ISIN IS NULL