选择数组中存在的值,但不在数据库中退出?

时间:2017-12-08 13:40:00

标签: postgresql

我有ID s:1 2 3 4 5的数据库。我需要返回我的数组中存在的元素(通常在IN ( ... )中指定的简单数据列表),但不要在DB中退出。 例如,检查值:1, 2, 3, 4, 5, 6, 7

因此查询应返回6, 7。我怎么能用PostgreSQL呢?

3 个答案:

答案 0 :(得分:1)

这可以使用select * from unnest(array[1,2,3,4,5,6]) as t(id) except select id from the_table

解决
select *
from unnest(array[1,2,3,4,5,6]) as t(id)
except
select id
from (values (1), (2), (3), (4) ) as the_table(id)

有一些测试数据:

id
--
 5
 6

返回

local config = "key1=type1\nkey2=type2\nkey3=type3"
local lines = {}
while true do
    local length = config:len()
    local s, f = config:find("\n")
    if s ~= nil then
        table.insert(lines, config:sub(1, s-1))
        config = config:sub(f+1, length)
    else
        table.insert(lines, config)
        break
    end
end

答案 1 :(得分:0)

如果您想要一个排除列表中所有元素的查询,可以使用NOT IN语句。

SELECT * FROM someTable WHERE id NOT IN (1, 2, 3, 4, 5);

在您的情况下,您可以从阵列中创建查询。

答案 2 :(得分:0)

with t (id) as (values (1),(2),(3),(4),(5))
select u.id
from
    t
    right join
    unnest(array[1,2,3,4,5,6,7]) u (id) on t.id = u.id
where t.id is null
;
 id 
----
  6
  7
相关问题