【发布时间】:2019-12-19 01:35:23
【问题描述】:
我有三个表A、B、C,我想从表B 的col_b 列中随机取一行,然后更新到表A。表C是表B的子表,用于过滤表B的数据。
这是我的sql语句:
update a a
set a.col_a_b =
(select t.col_b
from (select a1.col_a, b1.col_b, a1.rn_var
-- the number 6 is because I only have 6 rows of data,
-- and the real situation should be the total number of conditions in table b
from (select a0.col_a, TRUNC(dbms_random.value(1, 6)) rn_var
from a a0) a1
left join (select b.col_b, rownum rn
from b b
where exists (select 1
from c c
where b.id = c.col_b_id
and c.col_c = 'c1')) b1
on a1.rn_var = b1.rn) t
where t.col_a = a.col_a);
我发现了一个奇怪的现象:
如果我删除
a1.rn_var(from (select a1.col_a, b1.col_b, a1.rn_var行),它不会像我预期的那样工作在上面的基础上,如果我把
exists换成left join(或者join),结果是一样的如果我同时删除
a1.rn_var和exists,它会正常工作。
我知道可能有更好的方法来实现它,但谁能告诉我为什么?
更新:
其实是这个sql造成的:
select a1.col_a, b1.col_b -- remove a1.rn_var
from (select a0.col_a, TRUNC(dbms_random.value(1, 6)) rn_var from a a0) a1
left join (select b.col_b, rownum rn
from b b
where exists (select 1
from c c
where b.id = c.col_b_id
and c.col_c = 'c1')) b1
on a1.rn_var = b1.rn
-- this is for better display of results
where a1.col_a = 'a1';
在上面的sql中,我可能会得到多行数据或者列b1.col_b为空,如下图:
a1 b1
a1 b2
a1 b4
------------------------------------------------
a1 -- here is null
另外,a1.col_a 列的每个值都是一样的,我的意思是,如果值a1 有多行,那么值a2(等等)的结果是一样的,像这样:
a1 b2
a1 b4
a1 b5
a2 b2
a2 b4
a2 b5
...
【问题讨论】:
标签: oracle select random sql-update