我使用PHP访问SQL服务器数据库,我有2个数字存储为PHP变量。
例如,一个变量是10
,另一个变量是15
。
我需要输出一个“缺失”文档列表,即某个列col1
不包含10
和15
之间的数字的行。
示例:
col1
----
2
4
6
8
10
12
14
16
18
20
变量:
$start = 10
$end = 15
仅使用SQL的所需结果:
result
------
11
13
15
答案 0 :(得分:0)
如果您没有数字/统计表,则可以使用与LEFT JOIN
示例强>
Declare @R1 int = 10
Declare @R2 int = 15
Select Result= N
From (
Select Top (@R2-@R1+1)
N=@R1-1+Row_Number() Over (Order By (Select null))
From master..spt_values n1,master..spt_values n2
) A
Left Join YourTable B on A.N = B.[col1]
Where B.[col1] is null
<强>返回强>
Result
11
13
15
答案 1 :(得分:0)
您可以通过不同的方式实现这一点,一种方法是生成一个计数表并按左下方进行连接:
Declare @start int = 10
Declare @end int = 15
;With CTE_Numbers as (
Select top (@end - @start+1) RowN = @start + Row_number() over (order by (SELECT NULL)) -1
from master..spt_values s1, master..spt_values s2
)
Select c.RowN as Result from CTE_Numbers c
left join yourtable t
on c.RowN = t.col1
where t.col1 is null
答案 2 :(得分:0)
declare @t table (col1 int);
insert into @t values
(2),
(4),
(6),
(8),
(10),
(12),
(14),
(16),
(18),
(20)
declare @start int = 10,
@end int = 15;
with nums as
(
select n
from
(
select row_number() over(order by getdate()) n
from sys.all_columns c1 cross join sys.all_columns c2
) t
where n between @start and @end
)
select *
from nums
where not exists (select col1 from @t t where nums.n = t.col1);
答案 3 :(得分:0)
我会使用dbo.Numbers(Numbers PK)
table(reference #2)并跟随查询:
DECLARE @start INT = 10, @end INT = 15
SELECT x.Col1
FROM dbo.SourceTable x
WHERE x.Col1 >= @start AND x.Col1 <= @end
AND NOT EXISTS (
SELECT * FROM dbo.Numbers n
WHERE n.Number >= @start AND n.Number <= @end
AND n.Number = x.Col1
)