For example, I have php array $php_arr_to_check = array("green", "red", "blue");
And have many mysql rows like this
Id | TextToCheckIn
______________________
1 | green brown blue
2 | black yellow white red
3 | yellow green black red grey white
Want as if to loop $php_arr_to_check
through each row in column TextToCheckIn
and return Id
where, for example, at least 2 words from $php_arr_to_check
exists in TextToCheckIn
.
Is it possible? Does any mysql function exist?
Here is example with php (what I want to get)
$php_arr_to_check = array("green", "red", "blue");
echo '<pre>', print_r($php_arr_to_check, true), '</pre> php_arr_to_check <br/>';
$mysql_rows = array(
array("green", "brown", "blue"),
array("black", "yellow", "white", "red"),
array("yellow", "green", "black", "red", "grey", "white")
);
echo '<pre>', print_r($mysql_rows, true), '</pre> mysql_rows <br/>';
foreach( $mysql_rows as $one_row ){
//echo count(array_intersect($php_arr_to_check, $one_row)). ' count array_intersect __ <br/>';
if( count(array_intersect($php_arr_to_check, $one_row)) > 1 ){
$arr_with_count_matches[] = count(array_intersect($php_arr_to_check, $one_row));
$maches_exist = true;
}
}
echo '<pre>', print_r($arr_with_count_matches, true), '</pre> arr_with_count_matches <br/>';
Want to get the same result comparing php array to mysql column.
Any ideas how to do that (without LIKE
)? May be with MATCH AGAINST
somehow?
Before i used below, but got as if false positives....
SELECT
Id FROM table
WHERE MATCH (TextToCheckIn) AGAINST (?) LIMIT 1
Will try
SELECT
Id FROM table
WHERE MATCH (SUBSTRING_INDEX(TextToCheckIn, ' ', 3)) AGAINST (?) LIMIT 1
As understand I will compare first 3 words in TextToCheckIn
against php array. But do not understand what i will get. Reading here http://www3.physnet.uni-hamburg.de/physnet/mysql/manual_Fulltext_Search.html
For every row in a table it returns relevance - a similarity measure between the text in that row (in the columns that are part of the collection) and the query.
Seems it is exactly what is necessary... need to check
I think you want to use Boolean Full-Text Search
If you match without operators
+
-
against such asgreen red blue
all rows are returned, where a record contains at least one word:green
orred
orblue
.IN BOOLEAN MODE
and without operators each matched word will score1
. So if there's a record matching two out of the three words it would score2
.To get the rows with at least 2 score:
In Natural Language mode scoring works completely different. Think it's primarily based on BM25.
On large datasets boolean fulltext search (using a fulltext index) usually outperforms
REGEXP
orLIKE
by far if matching words somewhere in the text. Would only use like/regexp for matching from the initial such asREGEXP '^word'
orLIKE 'word%'
- if an index can be utilized.