Oracle-从查询中获取另一个查询中不存在的行

时间:2014-01-24 08:11:53

标签: sql oracle

假设我有两个问题::

查询1:

SELECT id, name, permission FROM table1

结果1:

+----+------+------------+
| id | name | permission |
+----+------+------------+
|  1 | A    | z          |
|  1 | A    | x          |
|  2 | B    | t          |
|  3 | C    | r          |
+----+------+------------+

查询2:

SELECT id, name, permission FROM table2

结果2:

+----+------+------------+
| id | name | permission |
+----+------+------------+
|  1 | A    | z          |
|  2 | B    | t          |
+----+------+------------+

我希望缺少权限作为输出:

+----+------+------------+
| id | name | permission |
+----+------+------------+
|  1 | A    | x          |
|  3 | C    | r          |
+----+------+------------+

我该怎么做?

3 个答案:

答案 0 :(得分:3)

在ORACLE中使用 MINUS 运算符,它将为您提供第一个表中不在秒中的所有行,即排除相互行:

SELECT id, 
       name, 
       permission 
FROM   table1 
MINUS 
SELECT id, 
       name, 
       permission 
FROM   table2;

答案 1 :(得分:1)

SELECT * 
FROM   table1 
WHERE  ( id, name, permission ) NOT IN (SELECT id, 
                                               name, 
                                               permission 
                                        FROM   table2); 

答案 2 :(得分:0)

这个是安全的NULL:

SELECT 
   t1.id
   , t1.name
   , t1.permission 
FROM table1 t1
WHERE NOT EXISTS
(
   SELECT 1 
   FROM table2 t2
   WHERE 
      t1.id = t2.id
      AND t1.name = t2.name
      AND t1.permission = t2.permission
)