0

我的数据库中有 27 个表。1个单词表(拼字游戏单词表),26个关联表。

Table  Fields
================
word   [id,word]
a      [word_id]
b      [word_id]
...
z      [word_id]

我试图找出给定字符串的匹配单词。

例如,如果给定的字符串是pant,我想知道:pant, apt, pat, tap, ant, tan, nap, pan, at, ta, pa, an, na

我目前的策略是分解字符串中的每个字母并找到与所有字母匹配的相关单词。

例如:

SELECT word.word
FROM word, p, a, n, t
WHERE
    word.id = p.word_id OR
    word.id = a.word_id OR
    word.id = n.word_id OR
    word.id = t.word_id

但这最终会打印出所有包含 ap、a、n 或 t 的单词。

如果我将所有运算符切换到AND,我只会遇到一场比赛:pant.

你能帮我解开这个谜吗?

我还关心如何处理字符串中的重复字母。例如,PPANT应该找到匹配的app,而普通的PANT不应该。

我在关联表的正确轨道上还是有更好的方法?

我试图在 php/mysql 中相当有效地处理这个问题。我知道之前有其他人在 C、perl、java 等语言中解决了这个谜题。

4

1 回答 1

1

我不熟悉 MySQL 的高级功能,所以我不能说是否有办法在程序上执行此限制,这可能会为您节省大量存储空间。尽管如此,我会提供这种可能性。

假设这是你的单词表:

+==========+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+
|   word   | a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |
+==========+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+
| pant     | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
+==========+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+
| ppant    | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
+==========+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+
| app      | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+==========+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+
| kick     | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+==========+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+

那么您的查询可能如下所示:

SELECT word.word FROM word
JOIN
(
  SELECT * FROM word WHERE word.word = "pant"
) AS root
ON
    word.a <= root.a
AND word.b <= root.b
AND word.c <= root.c
AND word.d <= root.d
AND word.e <= root.e
AND word.f <= root.f
AND word.g <= root.g
AND word.h <= root.h
AND word.i <= root.i
AND word.j <= root.j
AND word.k <= root.k
AND word.l <= root.l
AND word.m <= root.m
AND word.n <= root.n
AND word.o <= root.o
AND word.p <= root.p
AND word.q <= root.q
AND word.r <= root.r
AND word.s <= root.s
AND word.t <= root.t
AND word.u <= root.u
AND word.v <= root.v
AND word.w <= root.w
AND word.x <= root.x
AND word.y <= root.y
AND word.z <= root.z

现在,当然有一些方法可以规范化表和多种方法来创建查询。您应该尝试对您的情况最有意义的方法。

于 2012-10-28T03:50:37.217 回答