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

关于多个表中多个字段的distinct问题!
现有a,b2个表,其中
a表                             b表
列1                             列1
a                                 d
a                                 c
e                                 d
要求同时选出
a表                             b表
a                                   d
e                                   c

我用select   distinct   a.列1,   b.列1   from   a,b
这样得出来的结果是a表中的重复项没有消除,b中的消除了,请问这个问题怎么解决啊?

------解决方案--------------------
select a.列1,b.列1 from (select distinct 列1 from table1)a,(select distinct 列1 from table2)b
------解决方案--------------------
select distinct 列1 from 表1
union
select distinct 列1 frim 表2
------解决方案--------------------
这两个表中distinct出来的结果记录不见得相同,楼主非要把他们横向的在一起显示,是不合理的。
例如:
create table #temp1
(aa varchar(50))

insert into #temp1
select 'a '
union all
select 'b '
union all
select 'c '
union all
select 'c '

create table #temp2
(bb varchar(50))

insert into #temp2
select 'd '
union all
select 'd '
union all
select 'e '
union all
select 'f '
union all
select 'g '


select A.aa,B.bb from (select distinct aa from #temp1) A,(select distinct bb from #temp2) B

------
aa bb
a d
b d
c d
a e
b e
c e
a f
b f
c f
a g
b g
c g


如果非要在一起显示的话,还是纵向比较好,如ls所说,用union all

------解决方案--------------------
那你应该做两次SQL查询了。仅仅一次SQL查询,是得不到你需要的结果的