请问如何写SQL语句,将A表和B表中的数据合并,并标示出其来自哪张表。

A表: B表:
ID NAME ID NAME
1 A 2 B
2 B 3 C
3 C 4 D
要求得到以下结果:
ID NAME LY
1 A A
2 B AB
3 C AB
4 D B
请问如何写SQL语句,将A表和B表中的数据合并,并标示出其来自哪张表。其中LY列即来源列,注明来自A表或B表的数据

如果两表的ID字段上有唯一索引,下面SQL适合大部分的数据库而且语句运行起来会比较有效率。

select A.id,A.name ,'A' as ly from A where
not exists(select 1 from B where B.id=A.id and B.name=A.name)
union
select A.id,A.name ,'AB' from A where
exists(select 1 from B where B.id=A.id and B.name=A.name)
union
select B.id,B.name ,'B' from B where
not exists(select 1 from A where A.id=B.id and A.name=B.name)

如果没有可被利用的索引,上面语句在大数据量时效率低下(因为有not exists),建议运行下列语句(适合ORACLE数据库)

select t.id,t.name,
decode((max(t.f1) + max(t.f2)),1,'A‘,2,'B','AB') as ly from
(select id,name,1 as f1,0 as f2 from A
union all
select id,name,0 ,2 from B)t
group by t.id,t.name
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-11-06
select id,name, 'A' as LY from A where id not in (select id from t)
union
select id,name, 'B' as LY from B where id not in (select id from t)
union
(select A.id,A.name, 'AB' as LY from A,B where A.id=B.id and A.name=B.name) t追问

我的是oracle数据库,你的sql语句运行报错。另外,能否不用not in改用exists?

第2个回答  2013-11-06
select case(A.name) when null then B.name,'B'
when B.name then A.name,'AB'
else A.name,'A'
from A full join B on A.name=B.name
第3个回答  2013-11-06
CREATE TABLE A (
id    INT,
name  varchar(2)
);
INSERT INTO A VALUES(1, 'A');
INSERT INTO A VALUES(2, 'B');
INSERT INTO A VALUES(3, 'C');


CREATE TABLE B (
id    INT,
name  varchar(2)
);
INSERT INTO B VALUES(2, 'B');
INSERT INTO B VALUES(3, 'C');
INSERT INTO B VALUES(4, 'D');


SELECT
  NVL(a.id, b.id) AS ID,
  NVL(a.name, b.name) AS name,
  NVL2(a.id, 'A','') || NVL2(b.id, 'B','') AS LY
FROM
  A FULL JOIN B ON (A.id = B.id AND A.name=B.name)
ORDER BY
  ID;
  
        ID NAME LY
---------- ---- ----
         1 A    A
         2 B    AB
         3 C    AB
         4 D    B

第4个回答  2013-11-07
ansi标准写法:
select coalesce(a.id, b.id) id, coalesce(a.name,b.name) name,
case when a.id is null then 'B' when b.id is null then 'A' else 'AB' end ly
from a full join b on a.id=b.id
order by id
相似回答