2016-12-28 93 views
0

差距我想寫下一個選擇給我看不中我的數據庫中的所有物品。說我有一個名爲NRBEM列可能不具有任何縫隙名爲TBL795表。如何選擇我的SQLite數據庫

應該是這樣的:

inserir a descrição da imagem aqui

這些數字序列。

如果他們是這樣的:

inserir a descrição da imagem aqui

他們錯了,因爲有些項目還沒有被插入到表。

與項目是否存在任何差距,哪些是缺失的項目將很難找出一千表。

一個解決辦法是這樣的:

CREATE TABLE TESTE ( 
    NRBEM VARCHAR(15)) 

與這樣的指令的進給它:

INSERT INTO TESTE 
WITH RECURSIVE 
    cnt(NRBEM) AS (VALUES(1) UNION ALL SELECT NRBEM+1 FROM cnt WHERE NRBEM <100000) 
SELECT NRBEM FROM cnt A 

,並運行此選擇

SELECT A.NRBEM FROM TESTE A LEFT JOIN TBL795 B 
ON A.NRBEM = B.NRBEM 
WHERE B.NRBEM IS NULL 

我可以看到所有的項在我的表中缺失。

由於命令:

WITH RECURSIVE 
     cnt(NRBEM) AS (VALUES(1) UNION ALL SELECT NRBEM+1 FROM cnt WHERE NRBEM <100000) 
    SELECT NRBEM FROM cnt 

創建一個虛擬的表,我想運行一個選擇是這樣的:

SELECT NRBEM FROM (
WITH RECURSIVE 
    cnt(NRBEM) AS (VALUES(1) UNION ALL SELECT NRBEM+1 FROM cnt WHERE NRBEM <100000) 
SELECT NRBEM FROM cnt) A LEFT JOIN TBL795 B 
ON A.NRBEM = B.NRBEM 

但是,這是行不通的。

這樣:

SELECT X FROM (
WITH RECURSIVE 
    cnt(X) AS (VALUES(1) UNION ALL SELECT X+1 FROM cnt WHERE X <100000) 
SELECT X FROM cnt) A LEFT JOIN TBL795 B 
ON A.X = B.NRBEM 

它的工作原理,但不會選擇合適的項目。

所以,我怎麼能寫這樣選擇?

回答

1

這將有可能使用一個外連接和過濾掉比賽,但使用一套操作簡單:

WITH RECURSIVE CNT(NRBEM) AS (...) 
SELECT NRBEM 
FROM CNT 
WHERE NRBEM NOT IN (SELECT NRBEM 
        FROM tbl795); 
+0

其實第一次嘗試使用NOT IN是,但它沒」那麼T的工作,我搬到了LEFT JOIN。但是現在在我發現缺少的是數字轉換後,我重寫了第一個選擇,如下所示:SELECT X FROM( WITH RECURSIVE cnt(X)AS(VALUES(40)UNION ALL SELECT X + 1 FROM cnt WHERE X <50) SELECT X FROM cnt)WHERE X NOT IN(SELECT CAST(NRBEM AS NUMBER)FROM TBL795 WHERE NRBEM> = 40 AND NRBEM <= 50) 它也有效。 –

0

我發現我在做什麼錯。

如果我投nrbem爲數字選擇的作品。

SELECT A.X FROM (
WITH RECURSIVE 
    cnt(X) AS (VALUES(1) UNION ALL SELECT X+1 FROM cnt WHERE X <100000) 
SELECT X FROM cnt) A LEFT JOIN (SELECT CAST(NRBEM AS NUMBER) AS NRBEM FROM TBL795) B 
ON A.X = B.NRBEM 
WHERE B.NRBEM IS NULL 

如果我要檢查從項目2400年至2700年的範圍內,看看是否有任何差距,我可以做到這一點:

SELECT A.X FROM (
WITH RECURSIVE 
    cnt(X) AS (VALUES(2400) UNION ALL SELECT X+1 FROM cnt WHERE X < (2700)) 
SELECT X FROM cnt) A LEFT JOIN (SELECT CAST(NRBEM AS NUMBER) AS NRBEM FROM TBL795 WHERE NRBEM >= 2400 and nrbem <= 2700) B 
ON A.X = B.NRBEM 
WHERE B.NRBEM IS NULL 
LIMIT (2700 - 2400 + 1) 
相關問題