admin

SQL-如何从不在表中的where子句列表返回ID?

sql

给定这样的查询:

select customerId
  from customer
 where customerId in (
          1, 2, 3
       )

where子句列表中有数百个ID 。如何从不在表中的where子句中的列表返回ID ?

这是一个只能对它运行select查询的生产表。我只能运行select查询;我没有创建任何表的权限。


阅读 229

收藏
2021-06-07

共1个答案

admin

*对于大多数DBMS来说,这 *确实是一种非常残酷的方法 (除了需要使用Oracle之外,这是可行的select..from dual)。即使您无权访问创建/更新表, 并且只能 访问DB2,这也应该适用于DB2 SELECT

select N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N as NonExistentCustomerID
from (
    select 1 as N union all select 2 union all select 3 union all
    select 4 union all select 5 union all select 6 union all
    select 7 union all select 8 union all select 9 union all
    select 0) N1
cross join (
    select 1 as N union all select 2 union all select 3 union all
    select 4 union all select 5 union all select 6 union all
    select 7 union all select 8 union all select 9 union all
    select 0) N2
cross join (
    select 1 as N union all select 2 union all select 3 union all
    select 4 union all select 5 union all select 6 union all
    select 7 union all select 8 union all select 9 union all
    select 0) N3
cross join (
    select 1 as N union all select 2 union all select 3 union all
    select 4 union all select 5 union all select 6 union all
    select 7 union all select 8 union all select 9 union all
    select 0) N4
where N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N in (1,2,3)
    and not exists (
        select * from customer c where c.customerid = v.number + v2.number*1000)

根据需要展开子查询以覆盖您的整个号码范围。

如果您可以创建表 (或有一个方便的 ),请创建一个“数字”表,而不要使用数字0到9(10条记录),并保持自身连接

create table Numbers (N int)
insert into Numbers
select 1 union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9 union all
select 0

select N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N as NonExistentCustomerID
from numbers N1
cross join numbers N2
cross join numbers N3
cross join numbers N4
where N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N in (1,2,3)
    and not exists (
        select * from customer c where c.customerid = v.number + v2.number*1000)

一个numbers表始终是各种查询有用。

作为SQL Server的参考 ,假设数字在0-2047范围内,则可以使用

select v.number
from master..spt_values v
left join customer c on c.customerid = v.number
where v.type='P' and v.number in (1,2,3)
  and v.customerid is null

如果需要更大的范围,请继续连接到master..spt_values以获取更大的范围

select v.number + v2.number*1000 as NonExistentCustomerID
from master..spt_values v
inner join master..spt_values v2 on v2.type='P'
where v.type='P' and v.number + v2.number*1000 in (1,2,3)
  and v.number between 0 and 999
  and not exists (
    select * from customer c where c.customerid = v.number + v2.number*1000)
order by 1
2021-06-07