left join 後,左表怎樣合併或者去掉重複記錄
在使用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列變行