从不在表

时间:2018-04-23 07:20:57

标签: sql oracle

鉴于以下表格数据:

Students.id
-----------
1
2
3

如果我想从表中选择不在数字数组中的ID,我可以执行以下操作:

SELECT id FROM Students
WHERE id NOT IN (1, 3, 5);

Result: (2)

但我想做相反的事情 - 从数组中选择不在表格中的数字。我怎么能这样做?

到目前为止,我的尝试是:

Attempt 1:

SELECT id FROM TABLE(1, 3, 5)
WHERE id NOT IN (SELECT id FROM Students);

RESULT: ORA-00907: missing right parenthesis
------------------------
Attempt 2:

SELECT (1, 3, 5) FROM dual
WHERE ??? NOT IN (SELECT id from Students); -- not sure what the column name should be

RESULT: Executing the first line alone gives the error ORA-00907: missing right parenthesis
--------------
Attempt 3:

SELECT TABLE(1,3,5) AS ids FROM dual
WHERE ids NOT IN (SELECT id FROM Students);

RESULT: ORA-00936: missing expression

期望的结果(来自我的例子):( 5)

注意:我找到了this related question, but alas it is also unanswered。和Fuzz一样,我的数字数组也没有存储在表格中。

3 个答案:

答案 0 :(得分:1)

您可以尝试反对将包含您的ID号的CTE加入Students表:

WITH cte AS (
    SELECT 1 AS id FROM dual UNION ALL
    SELECT 3 FROM dual UNION ALL
    SELECT 5 FROM dual
)

SELECT t1.id
FROM cte t1
LEFT JOIN Students t2
    ON t1.id = t2.id
WHERE t2.id IS NULL

如果您的数据位于正确的表格中,您可以使用联接或其他一些方法轻松获得您的要求。如果您对此有长期需求,那么我建议您将数据放入表格中。

我们也可以使用EXISTS编写上述查询,这可能会有更好的效果:

SELECT t1.id
FROM cte t1
WHERE NOT EXISTS (SELECT 1 FROM Students t2 WHERE t1.id = t2.id)

答案 1 :(得分:1)

您可以以正确的方式使用表构建,例如:使用union而不是数组:

  select id from (
  select 1 id  from dual 
  union 
  select 3  from dual 
  union 
  select 5  from dual ) t 
  where t.id NOT IN (
  SELECT id FROM Student
  )

答案 2 :(得分:1)

您可以创建一个集合类型:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TYPE NumbersList IS TABLE OF NUMBER;

然后您可以在查询中使用它:

查询1

SELECT id
FROM   students
WHERE  id NOT MEMBER OF NumbersList( 1, 3, 5 )

<强> Results

| ID |
|----|
|  2 |

或者,要反转它并使集合中的数字不在表中,您可以使用表集合表达式(TABLE(:your_collection)):

查询2

SELECT COLUMN_VALUE
FROM   TABLE( NumbersList( 1, 3, 5 ) )
WHERE  COLUMN_VALUE NOT IN ( SELECT id FROM students )

<强> Results

| COLUMN_VALUE |
|--------------|
|            5 |

您甚至可以将集合作为绑定变量传递(examples从PL / SQL和Java数组传递它。)