我的应用程序获取书籍并将此书的每个单词插入数据库,它可能有超过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 :(得分: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'
<强>结果:强>
答案 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