日期:2014-05-16  浏览次数:20785 次

============求一条SQL语句(Oracle数据库)============
背景:
1:Oracle数据库

2:有一个数据表tableA,它包括一列TelphoneNum。

3:还有若干个表,tableB,tableC,tableD,.....tableN,这些表中也包括了一个TelphoneNum的字段。

要求实现:

1:tableA中的TelphoneNum,如果没有在tableB,tableC,tableD,.....tableN出现过,那么从tableA表中把此TelphoneNum相关的信息选取出来。

2:如果tableA中的TelphoneNum在tableB,tableC,tableD,.....tableN中的任意一个表中出现过。那么也要选取出来,标记他是在那一个表中出现过。

3:没有出现的TelphoneNum要排在已经出现过的TelphoneNum之前

最后效果,例如:
---------------------
手机品牌|厂商|手机号码(TelphoneNum)|是否出现
---------------------
A        |A    |13912345678            |
B        |B    |13912345679            | 

C        |C    |13001234567            |在tableB中出现过
D        |D    |13000000000            |在tableN中出现过 
---------------------


谢谢。

------解决方案--------------------
先把tableB到tableN建一个view,包含TelphoneNum和表名。
create view tableBtoN as
select TelphoneNum,'tableB' tablename from tableB
union all
select TelphoneNum,'tableC' tablename from tableC
union all
...
select TelphoneNum,'tableN' tablename from tableN

然后
select TelphoneNum,(select tablename from tableBtoN t2 where t1.TelphoneNum=t2.TelphoneNum and rownum=1) "是否出现过" from tableA


------解决方案--------------------
直接将这些表关联,也是一种办法。

是否出现过 一列,换成 A B C ... N 的 N列
------解决方案--------------------
union all ..
------解决方案--------------------
select t1.TelphoneNum,t2.tablename
from tableA t1,
(select TelphoneNum,'tableB' tablename from tableB
union all
select TelphoneNum,'tableC' tablename from tableC
union all
...
select TelphoneNum,'tableN' tablename from tableN) t2
where t1.TelphoneNum = t2.TelphoneNum(+)
------解决方案--------------------

select tableA.手机品牌, tableA.厂商,
       tableA.TelphoneNum 
------解决方案--------------------
 (select decode(nvl(count(1),0), 0, '', '
------解决方案--------------------
在tableB中出现过') from tableB where tableA.TelphoneNum =tableB.TelphoneNum)