问题
I am in the middle of building my anagram query which is almost working great. Here is my sql
The letters I am using are "settin?"
The difference is the wildcard which I will allow the user to add a "?" into the field.
SELECT `word`, 0+ABS(`e`-1)+ABS(`i`-1)+ABS(`n`-1)+ABS(`s`-1)+ABS(`t`-2) AS difference
FROM `TWL06`
WHERE LENGTH(`word`) <= 7
HAVING difference <= 1
My Table Structure is as
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 |
--------------------------------------------------------------------------------------------------------------
THIS | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
The problem with the query is that it will only pull words that contain all the letters with a difference of 0 or 1. It will not pull words that may be smaller in length that could contain some of the letters or shorter words like 2 3 4 5 6 letters long.
I thought WHERE LENGTH(word
) <= 7 would take care of the length, but that seems to not work.
For Instance: SIT, TENTS, TEST
or even words with a difference of 1 wildcard like
TESTY (Y is the wildcard)
Any ideas?
回答1:
populated a table: anagram (word, sorted_word)
where word
contains "setting", "apple", etc. and sorted_word
contains "eginstt", "aelpp", etc.
to find anagrams of setting, first get the sorted word: select sorted_word from anagram where word = "setting"
then use that sorted word to get all anagrams: select word from anagram where sorted_word = "eginstt"
you can do it in a single query too.
回答2:
Found a fix for it
SELECT
`word`,
0+IF(`a` > 0, `a` - 0, 0)
+IF(`b` > 0, `b` - 0, 0)
+IF(`c` > 0, `c` - 0, 0)
+IF(`d` > 0, `d` - 0, 0)
+IF(`e` > 1, `e` - 1, 0)
+IF(`f` > 0, `f` - 0, 0)
+IF(`g` > 0, `g` - 0, 0)
+IF(`h` > 0, `h` - 0, 0)
+IF(`i` > 1, `i` - 1, 0)
+IF(`j` > 0, `j` - 0, 0)
+IF(`k` > 0, `k` - 0, 0)
+IF(`l` > 0, `l` - 0, 0)
+IF(`m` > 0, `m` - 0, 0)
+IF(`n` > 1, `n` - 1, 0)
+IF(`o` > 0, `o` - 0, 0)
+IF(`p` > 0, `p` - 0, 0)
+IF(`q` > 0, `q` - 0, 0)
+IF(`r` > 0, `r` - 0, 0)
+IF(`s` > 1, `s` - 1, 0)
+IF(`t` > 2, `t` - 2, 0)
+IF(`u` > 0, `u` - 0, 0)
+IF(`v` > 0, `v` - 0, 0)
+IF(`w` > 0, `w` - 0, 0)
+IF(`x` > 0, `x` - 0, 0)
+IF(`y` > 0, `y` - 0, 0)
+IF(`z` > 0, `z` - 0, 0) AS difference
FROM `TWL06`
WHERE LENGTH(`word`) <= 8
HAVING difference <= 2
来源:https://stackoverflow.com/questions/17285723/mysql-anagram-query-to-pull-every-possible-word-with-any-letters