简体   繁体   中英

LIKE CONCAT vs REGEXP mysql

I want to select the row of my mysql database which contains a word from a string, which is a php variable. I found two ways:

"SELECT * FROM table WHERE '$string' REGEXP word_column"

and

"SELECT * FROM table WHERE '$string' LIKE CONCAT('%',word_column,'%')"

For example, if my database is:

id | word_column
 0 | red
 1 | blue
 2 | green
 ...

Then

<?php
...
$string = 'This string contains word red, so I want mysql to return row 0!';
$best_query = ""; //HERE GOES ONE OF THE QUERIES ABOVE
$result_i_want = mysqli_query($db_connect, $best_query);
...
?>

Both queries works, but which is the one with best performance?

"SELECT * FROM table WHERE '$string' LIKE CONCAT('%',word_column,'%')"

is faster. As commenters noted, performance depends upon on your dataset to some extent also.

For searching for the entire column , don't use LIKE or REGEXP :

SELECT ... WHERE word_column = '$string'
-- and have
INDEX(word_column)

For searching for word(s) embedded in a string :

SELECT ... WHERE MATCH(string_column) AGAINST ('+$string' IN BOOLEAN MODE)
-- and have
FULTEXT(string_column)

(Study the documentation about FULLTEXT; there are some restrictions.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM