获取具有特定条件的所选行的行之前和之后

时间:2014-11-25 08:40:58

标签: sql sql-server tsql row

我的应用程序获取书籍并将此书的每个单词插入数据库,它可能有超过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

2 个答案:

答案 0 :(得分:2)

使用Join获取SQL Server 2005加上的预期结果。

    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

答案 1 :(得分: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