2014-11-25 48 views
1

我的應用程序獲取書籍並將這本書的每個單詞插入數據庫,它可能在書中有超過1億個單詞並插入到數據庫中。 現在我想要獲得與上一個和下一個單詞的特定單詞。 獲得結果的時間非常重要。獲取具有特定條件的選定行的行之前和之後

舉例說: 「這本書的話在這個表中插入此處...」

------------------------------ 
|  ID  | word  | 
------------------------------ 
|  1  |  the  | 
|  2  |  book | 
|  3  |  words | 
|  4  |  insert | 
|  5  |  here | 
|  6  |  in  | 
|  7  |  this | 
|  8  |  table | 
|  .  |  .  | 
|  .  |  .  | 
|  .  |  .  | 
------------------------------ 

或其他例如:

------------------------------ 
|  ID  | word  | 
------------------------------ 
|  1  |  my  | 
|  2  |  name | 
|  3  |  is  | 
|  4  |  joseph | 
|  5  |  and  | 
|  6  |  my  | 
|  7  |  father | 
|  8  | name  | 
|  9  |  is  | 
|  10  | brian | 
------------------------------ 

我想過去和未來同一單詞的值

例如,我想獲取「name」的前一個和下一個單詞:

-------------------------- 
| my | name | is | 
-------------------------- 
| father | name | is | 
-------------------------- 
其他相關崗位的朋友

寫代碼,但是這個代碼需要很長時間才能得到結果,我想快速得到結果表:

相關信息:[提問] Get previous and next row from rows selected with (WHERE) conditions

+0

多久做你計劃運行該查詢RY? – 2014-11-25 08:50:02

回答

0

我在我的文字裏列上創建索引,並設置該代碼來獲得快速結果:

WITH CTE AS 
(SELECT * FROM WordsTable WHERE word=N'Name') 
SELECT   
    t2.word AS previousWord, 
    t1.word, 
    t3.word AS nextWord 
FROM 
    WordsTable AS t2, 
    CTE AS t1, 
    WordsTable AS t3 
WHERE 
    (t2.ID + 1)= t1.ID AND 
    (t3.ID - 1) = t1.ID 
2

使用Join到獲得SQL Server 2005 plus的預期結果。

create table words (id integer, word varchar(20)); 

    insert into words 
    values 
    (1 ,'my'), 
    (2 ,'name'), 
    (3 ,'is'), 
    (4 ,'joseph'), 
    (5 ,'and'), 
    (6 ,'my'), 
    (7 ,'father'), 
    (8 ,'name'), 
    (9 ,'is'), 
    (10,'brian'); 

SELECT A.Id , C.word AS PrevName , 
       A.word AS CurName , 
       B.word AS NxtName 
FROM words AS A 
LEFT JOIN words AS B ON A.Id = B.Id - 1 
LEFT JOIN words AS C ON A.Id = C.Id + 1 
WHERE A.Word = 'name' 

結果:

enter image description here

Fiddler Demo

相關問題