union后数据少了,不能包含重复行
之前一直关注union在两个表的连接后出现的不包含重复行,我这次是在分组数据后进行两个结果集的union。分组后的数据如下,出现了两个时间完全相同的数据,导致了我再用union连接的时候只出现了一条数据。
我在用的时候一直有个问题困扰了我,因为我的union的结果集一个空的,导致了我一直误以为是空数据集的问题。如下面的展示的sql代码,查询的结果为18条。
select *
from (select dtlrf.jyje,
dtlrf.yhid,
nvl(to_number(dtlrf.zjlx), 0) zjlx,
dtlrf.czybh,
dtlrf.czyxm,
dtlrf.jysj
from ipay.order_detl dtlrf
where 1 = 1
and dtlrf.paystate = 'repaid'
and (dtlrf.cqtfbs not in ('1', '2') or dtlrf.cqtfbs is null)
and dtlrf.czybh = '493'
and dtlrf.jyje = 500
and dtlrf.jysj >= '20210406000000'
and dtlrf.jysj <= '20210406235918'
union
-- 下面的sql 查询结果为空
select cash.jyje,
'XJZF' yhid,
0 zjlx,
cash.czybh,
cash.czyxm,
cash.jysj
from ipay.overtocash_refund cash
where 1 = 1
and cash.state = 'repaid'
and cash.czybh = '493') a
order by a.jysj
查询的的结果集:
第二个这种情况下的查询结果为19条,没有用union。相同的数据会展示出来。
select dtlrf.jyje,
dtlrf.yhid,
nvl(to_number(dtlrf.zjlx), 0) zjlx,
dtlrf.czybh,
dtlrf.czyxm,
dtlrf.jysj
from ipay.order_detl dtlrf
where 1 = 1
and dtlrf.paystate = 'repaid'
and (dtlrf.cqtfbs not in ('1', '2') or dtlrf.cqtfbs is null)
and dtlrf.czybh = '493'
and dtlrf.jyje = 500
and dtlrf.jysj >= '20210406000000'
and dtlrf.jysj <= '20210406235918'
order by dtlrf.jysj
查询结果为:
总结:
union的优势会对数据集进行:
1.排序
2.去重
但是如果有完全相同的数据情况下就会漏掉,我之前觉得不会有两笔交易的时间会完全相同,但是看来完全有可能存在的。所以分组之后的数据字段一般比较少,重复的概率也会增大,在没有排序的情况下,union一定要慎用。union all也是不错的选择。