日期:2014-05-18  浏览次数:20530 次

三张表联合查询,并过滤重复数据的问题,请教【谢谢】
a表字段:
姓名,年龄,性别
b表字段:
姓名,住址,消费B
c表字段:
姓名,电话,消费C

我要显示结果为
姓名,年龄,性别,消费B,消费C

a表中在b,c表中姓名相同的记录的消费b和消费c,如同个姓名在a,b,c表中存在多次,则过滤重复,任意取一个。
例:
a表字段:
姓名,年龄,性别
王二,18,男
王二,19,男
张三,18,男
b表字段:
姓名,住址,消费B
王二,18,电视
张三,19,电视
张三,20,冰箱
c表字段:
姓名,电话,消费C
王二,18,西瓜
王二,19,南瓜
张三,18,冰糕
张三,19,冰水

最后查询的结果应该为:
姓名,年龄,性别,消费B,消费C
王二,18, 男, 电视 西瓜
张三,18, 男, 电视 冰糕
-----------------------------------------
请问这样的sql语句怎么写啊?谢谢各位大哥了,我想了一天了

------解决方案--------------------
直接inner join
------解决方案--------------------
表设计成这个样子。。晕死 什么记录阿
------解决方案--------------------
select *,id=identity(int,1,1) into # from a inner join b on a.姓名-b.姓名 inner join c on a.姓名=c.姓名
select * from # a where not exists (select 1 from # b where a.id<b.id)
------解决方案--------------------
SQL code

---------------------------------
--  Author: htl258(Tony)
--  Date  : 2009-08-05 23:02:31
---------------------------------
--> 生成测试数据表:a

If not object_id('[a]') is null
    Drop table [a]
Go
Create table [a]([姓名] nvarchar(2),[年龄] int,[性别] nvarchar(1))
Insert a
Select '王二',18,'男' union all
Select '王二',19,'男' union all
Select '张三',18,'男'
Go
--Select * from a

--> 生成测试数据表:b

If not object_id('[b]') is null
    Drop table [b]
Go
Create table [b]([姓名] nvarchar(2),[住址] int,[消费B] nvarchar(2))
Insert b
Select '王二',18,'电视' union all
Select '张三',19,'电视' union all
Select '张三',20,'冰箱'
Go
--Select * from b

--> 生成测试数据表:c

If not object_id('[c]') is null
    Drop table [c]
Go
Create table [c]([姓名] nvarchar(2),[电话] int,[消费C] nvarchar(2))
Insert c
Select '王二',18,'西瓜' union all
Select '王二',19,'南瓜' union all
Select '张三',18,'冰糕' union all
Select '张三',19,'冰水'
Go
--Select * from c

-->SQL查询如下:
select a.*,b.消费B,c.消费C 
from (select * from a t where not exists(select 1 from a where [姓名]=t.[姓名] and [年龄]<t.[年龄])) a
  left join (select * from b t where not exists(select 1 from b where [姓名]=t.[姓名] and [住址]<t.[住址])) b
    on a.姓名=b.姓名
  left join (select * from c t where not exists(select 1 from c where [姓名]=t.[姓名] and [电话]<t.[电话])) c
    on a.姓名=c.姓名
/*
姓名   年龄          性别   消费B  消费C
---- ----------- ---- ---- ----
王二   18          男    电视   西瓜
张三   18          男    电视   冰糕

(2 行受影响)
*/

------解决方案--------------------
SQL code

select distinct a.*,b.消费B,c.消费C from [a] , b ,c
where a.姓名=b.姓名 and a.姓名=c.姓名
and not exists(select 1 from a t where 姓名=a.姓名 and 年龄<a.年龄)
and not exists(select 1 from b t where 姓名=b.姓名 and 住址<b.住址)
and not exists(select 1 from c t where 姓名=c.姓名 and 电话<c.电话)