日期:2014-05-18  浏览次数:20595 次

数据库查询的问题
我现在有个表A 字段id

有5条数据 1,2,3,5,6

然后我现在要查询的是 怎么通过ID查询到 “4”(也就是说ID里面不包含的那个数字)

ID可以当作是累加的,中间可能有个别漏掉的,我现在就是想把漏掉的给找出来 

小白 求教

------解决方案--------------------
数据量多么?是SQL2005还是?

SQL code

--SQL2005

;with ach as
(
    select rid=row_number() over (order by getdate())
    from master..spt_values a,master..spt_values b
    where a.type = 'P' and b.type = 'P'
)

select a.rid
from ach a left join tb b on a.rid = b.id
where b.id is null

------解决方案--------------------
SQL code

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'A')
BEGIN
    DROP TABLE A
END
GO
CREATE TABLE A
(
    ID INT
)
GO

INSERT INTO A
SELECT 1 UNION
SELECT 2 UNION
SELECT 3 UNION
SELECT 5 UNION
SELECT 6 UNION
SELECT 8 

GO

SELECT number
FROM A FULL OUTER JOIN (SELECT number FROM master..spt_values WHERE type = 'P' AND number > 0) AS B ON number = ID
WHERE number <= (SELECT MAX(ID) FROM A) AND number >= (SELECT MIN(ID) FROM A) AND ID IS NULL

number
4
7