SELECT (b.descr || ' - ' || c.descr) description FROM tbl1 a LEFT JOIN tbl2 b ON a.ACCOUNT = b.ACCOUNT LEFT JOIN tbl3 c ON a.product = c.product WHERE a.descr50 = ' ' ;
table1只有7622行descr50 =”但是这个选择返回7649行.你能帮帮我吗?提前致谢
解决方法
当您将两个或多个表连接在一起时,您可以有效地获取这些表的笛卡尔积,并应用JOIN条件中指定的过滤器.
当您使用过时的隐式JOIN语法时,这一点更为明显.
LEFT JOIN保证您获得的行数不会低于最左边的表所包含的行数,即.即最左边的表中的每一行至少返回一次.
如果过滤器不是一对一行映射,您仍然可以获得更多行.
在你的情况下:
SELECT (b.descr || ' - ' || c.descr) description FROM tbl1 a LEFT JOIN tbl2 b ON b.ACCOUNT = a.ACCOUNT LEFT JOIN tbl3 c ON c.product = a.product WHERE a.descr50 = ' '
帐户或产品在b或c中不是唯一的.
对于这些行:
a.account 1 2 3 b.account b.description 1 Account 1 2 Account 2 - old 2 Account 2 - new
,JOIN将返回以下内容:
a.account b.account b.description 1 1 Account 1 2 2 Account 2 - old 2 2 Account 2 - new 3 NULL NULL
,为您提供比任何一个表包含更多的行.
要从任一表中选择第一个匹配的描述,请使用:
SELECT ( SELECT FIRST_VALUE(descr) OVER (ORDER BY descr) FROM tbl2 b WHERE b.account = a.account AND rownum = 1 ) || ' - ' || ( SELECT FIRST_VALUE(descr) OVER (ORDER BY descr) FROM tbl3 c WHERE c.product= a.product AND rownum = 1 ) description FROM tbl1 a WHERE a.descr50 = ' '
要进行更新,只需将查询包装到内联视图中:
UPDATE ( SELECT ( SELECT FIRST_VALUE(descr) OVER (ORDER BY descr) FROM tbl2 b WHERE b.account = a.account AND rownum = 1 ) || ' - ' || ( SELECT FIRST_VALUE(descr) OVER (ORDER BY descr) FROM tbl3 c WHERE c.product= a.product AND rownum = 1 ) description FROM tbl1 a WHERE a.descr50 = ' ' ) SET descr50 = description