如何覆盖SQL * Plus中的优先级?

时间:2010-10-15 17:27:03

标签: sql sqlplus

select * from tab1
minus
select * from tab2
union
select * from tab2
minus
select * from tab1

如何确保将其解析为?

((select * from tab1
minus
select * from tab2)
union
(select * from tab2
minus
select * from tab1))

1 个答案:

答案 0 :(得分:1)

你可以在FROM子句中使用带括号的表达式吗?

SELECT *
FROM ((select * from tab1 minus select * from tab2)
      UNION
      (select * from tab2 minus select * from tab1)) AS symdiff

如果表在等效列上具有主键,则可以使用:

SELECT tab1.*
  FROM tab1
 WHERE tab1.pk NOT IN (SELECT tab2.pk FROM tab2)
UNION -- optionally UNION ALL
SELECT tab2.*
  FROM tab2
 WHERE tab2.pk NOT IN (SELECT tab1.pk FROM tab2)

然而,这是因为没有什么能阻止表tab1(pk,othercol)有一行(pk = 1,othercol = 2)而tab2(pk,othercol)包含一行(pk = 1,othercol = 3) 。这是你必须要小心的事情 - 我曾经被一次糟糕的假设所困扰。