Query where sum of specified columns (all ints) in row are less than a specified int

时间:2015-10-29 15:43:49

标签: php mysql sql myisam

I'm writing a word search program.

My database is set up to MyISAM with one table (Words) structured

WordID | String | A | B | ... | Z |
------------------------------------
int     varchar int  int ...  int

Where the values for columns A - Z are the # of occurrences of that letter in the string.

To write a query to find all possible words made out of a specified (but dynamic - user chosen) set of characters (including wild characters) ie: "Bu!!er" should return but, butt, bull, etc

Where

 S is the set of characters specified that we can use
 W is the set of characters in a word

I'll need to query the database for all strings where

 # of occurences in the word for each specified character (not including "!") is less than number of occurrences of that character in the specified string
W_k < S_k where k is each character specified

AND

# of occurrences of letters not specified in the specified string are in SUM less than the total occurrences of the wildcard character ("!") in the specified string 
W_q < S_! where q is each character not specified and S_! total amount of occurrences of "!".

For the first part of the WHERE statement (W_k < S_k) For bu!!er the statement would be

 `B` <= 1 AND `U` <= 1 AND `E` <= 1 AND `R` <= 1

And for the second part

 `A` + `C` + `D` + ... + `Z` <= 2

The complete Where part of the query becomes

  ( ( `A` + (IF(`B`-1 < 0, 0, `B`-1)) + `C` + `D` + (IF(`E`-1 < 0, 0, `E`-1)) + `F` + `G` + `H` + `I` + `J` + `K` + `L` + `M` + `N` + `O` + `P` + `Q` + (IF(`R`-1 < 0, 0, `R`-1)) + `S` + `T` + (IF(`U`-1 < 0, 0, `U`-1)) + `V` + `W` + `X` + `Y` + `Z` ) <= 2 ) 

Is there a better way to do it than this?

1 个答案:

答案 0 :(得分:1)

 `A` + `C` + `D` + ... + `Z`

使用非规范化?将全长存储在单独的列中。

 `TOTAL` <= 5

作为旁注:

您的架构过多地限制了可能的查询 - 尽管这对于这项工作来说已经足够了。将所有单词保留在内存中(每个服务器实例一个)并在单词上执行“全表扫描”或“索引扫描”可能会更好。