我有一个大表,其中包含来自文本文件的单词(offset_1只是offset-1):

file  offset offset_1 word
----  ------ -------- ----
1.txt   1       0     I
1.txt   2       1     have
1.txt   3       2     a
1.txt   4       3     large
1.txt   5       4     table
1.txt   6       5     that
1.txt   7       6     contains

我想在给定的距离或更短的距离内找到一对单词。例如,“a”和“table”之间最多有一个单词。
我现在做的是(在MySQL中):
SELECT t1.offset, t3.offset
FROM t as t1 JOIN t as t2 JOIN t as t3
ON t2.file = t1.file AND t3.file = t1.file AND
(
     (t1.offset = t2.offset_1 AND t2.offset = t3.offset_1) # "a large table"
  OR (t1.offset = t3.offset_1 AND t2.offset = 1)           # "a table"
)
WHERE t1.word = 'a' AND t3.word = 'table'

但这永远不会终止(表很大)。
如果我在或下移除这两个条件中的任何一个,它将工作并正确地分别找到“大表”或“表”。
正确的方法是什么?

最佳答案

我建议使用union all将其分为两个查询。像这样的:

SELECT t1.offset, t3.offset
FROM t t1 JOIN
     t t2
     ON t2.file = t1.file AND t1.offset = t2.offset_1
WHERE t1.word = 'a' AND t2.word = 'table'
UNION ALL
SELECT t1.offset, t3.offset
FROM t t1 JOIN
     t t2
     ON t2.file = t1.file AND t1.offset = t2.offset_1 JOIN
     t t3
     ON t3.file = t2.file and t2.offset = t3.offset_1
WHERE t1.word = 'a' AND t3.word = 'table';

OR中的JOIN条件通常对性能有不良影响。有时将逻辑分为多个子查询是一个很大的胜利

关于mysql - MySQL:链式推理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31451030/

10-11 05:03
查看更多