日期:2014-05-18 浏览次数:20591 次
select a.name,b.phone from a join b on a.pid=b.id and a.type='b' union all select a.name,c.phone from a join b on a.pid=c.id and a.type='c'
------解决方案--------------------
select a.name,b.phone from a, (select id,phoneb as phone from b union all select id,phonec as phone from c)b where a.id=b.id
------解决方案--------------------
SELECT A.NAME,B.PHONEB AS PHONE FROM A INNER JOIN B ON A.PID = B.ID WHERE A.TYPE = 'B' UNION ALL SELECT A.NAME,C.PHONEC FROM A INNER JOIN C ON A.PID = C.ID WHERE A.TYPE = 'C'
------解决方案--------------------
select a.name,b.phone from a join b on a.pid=b.id and a.type='b' union all select a.name,c.phone from a join b on a.pid=c.id and a.type='c'
------解决方案--------------------
select a.name,b.phone from a join (select 'b' as type,id,phoneb as phone from b union all select 'c' as type,id,phonec as phone from c ) b on a.type=b.type and a.pid=b.id
------解决方案--------------------
---------------------------- -- Author :fredrickhu(小F,向高手学习) -- Date :2011-11-10 13:47:55 -- Version: -- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) -- Apr 22 2011 11:57:00 -- Copyright (c) Microsoft Corporation -- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64) -- ---------------------------- --> 测试数据:[A] if object_id('[A]') is not null drop table [A] go create table [A]([type] varchar(1),[pid] int,[name] varchar(2)) insert [A] select 'B',1,'aa' union all select 'B',2,'bb' union all select 'C',1,'cc' --> 测试数据:[B] if object_id('[B]') is not null drop table [B] go create table [B]([id] int,[phoneB] varchar(12)) insert [B] select 1,'010-12345678' union all select 2,'011-12345678' --> 测试数据:[C] if object_id('[C]') is not null drop table [C] go create table [C]([id] int,[phoneC] varchar(12)) insert [C] select 1,'012-12345678' --------------开始查询-------------------------- select a.name,b.phone from (select px=row_number()over(order by getdate()),* from a)a, (select px=row_number()over(order by getdate()),* from(select id,phoneb as phone from b union all select id,phonec as phone from c)t)b where a.px=b.px ----------------结果---------------------------- /* name phone ---- ------------ aa 010-12345678 bb 011-12345678 cc 012-12345678 (3 行受影响) */