问题
Working with MySQL and I can't find the right combination of terms for this expression.
Using a PHP user input variable in my statement, I need to find a partial substring match and group by the full match word
Taking example input "#bea" I want to find matches for "#bea" as a substring in full text posts, then group by and count the full word where it matches such as "#beat", "#beauty", "#beast"
With example posts in database
Testing Post #beat #beauty
Another test #beauty #beast
Testing #boom #beast
I want to search for a substring, example "#bea"
and have the output
Match | Count
#beast | 2
#beauty | 2
#beat | 1
Can this be done with MySQL or am I better finding matches and counting full words using a PHP algorithm?
回答1:
Try this:
SELECT A.word `Match`, COUNT(B.sentence) `Count`
FROM
(SELECT '#beast' word UNION ALL
SELECT '#beauty' word UNION ALL
SELECT '#beat' word) A LEFT JOIN Sentence B
ON INSTR(B.sentence,A.word)>0
GROUP BY A.word
ORDER BY `Count` DESC, A.word;
See DEMO on SQL Fiddle and INSTR() function.
回答2:
You can use below query to find count of each word.
SELECT
sum(INSTR( '#beast' , TABLE.COL) > 0) '#beast',
sum(INSTR( '#beauty' , TABLE.COL) > 0) '#beauty'
FROM
TABLE
Then you can pivot table if needed; MySQL pivot table
来源:https://stackoverflow.com/questions/49004151/mysql-finding-substring-matches-and-group-by-match-full-word