在使用left join 后会发现如果右表数量有重复的话,查询出来的数量大于左表的数量,
如 表一 test1
ID | NAME | SEX | AGE | ||
1 | 1 | 1 | 1 | ||
2 | 2 | 2 | 1 | ||
3 | 3 | 3 | 1 |
表二 test2
ID | NAME | SEX | KJXYH |
1 | 1 | 1 | kjxy-物采中心-20130001 |
2 | 1 | 1 | kjxy-物采中心-20130003 |
3 | 1 | 1 | kjxy-物采中心-20130002 |
普通的left join
Select t1.* ,test2.kjxyh From test1 t1 Left Join test2 On t1.Name = test2.Name And t1.sex =test2.sex
查询出来的结果:
ID | NAME | SEX | AGE | KJXYH |
1 | 1 | 1 | 1 | kjxy-物采中心-20130001 |
1 | 1 | 1 | 1 | kjxy-物采中心-20130003 |
1 | 1 | 1 | 1 | kjxy-物采中心-20130002 |
2 | 2 | 2 | 1 | |
3 | 3 | 3 | 1 |
查询结果为五条数据,不是我们想要的结果,下面看看如果我用这种方式查询的结果
select test1.*,t2.kjxyh from test1 left join(
Select * From
(
select a.*,row_number() over(partition by Name,sex order by id) r
from test2 a
) where r = 1 ) t2
on test1.Name = t2.Name And test1.sex = t2.sex
ID | NAME | SEX | AGE | KJXYH |
1 | 1 | 1 | 1 | kjxy-物采中心-20130001 |
2 | 2 | 2 | 1 | |
3 | 3 | 3 | 1 |
会发现数据如只有三条了。按照排序获取到了三条,以左表为基表,然后从test2中按照指定的排序获取到了test2中的kjxyh,但是有时候需要展示所有的kjxyh该怎么办呢,看看下面这条sql语句:
select test1.*,b.kj from test1,
( select test1.id,wm_concat(test2.kjxyh) kj from test1
left join test2 on test1.name=test2.name and test1.sex=
test2.sex group by test1.name,test1.sex,test1.id) b
where test1.id in(b.id)
查询结果:
ID | NAME | SEX | AGE | KJ |
1 | 1 | 1 | 1 | kjxy-物采中心-20130001,kjxy-物采中心-20130003,kjxy-物采中心-20130002 |
2 | 2 | 2 | 1 | |
3 | 3 | 3 | 1 |
这样在kj这一列就展示了所有的kjxyh,是否满足你的要求呢?
wm_concat列变行