开发者

How to select based on keyword or string in mysql database?

开发者 https://www.devze.com 2023-03-23 16:34 出处:网络
I\'m making my search function but I don\'t know how to select only rows that contain the search terms. The idea would be to select only rows with the string $search from the table lines开发者_JS百科

I'm making my search function but I don't know how to select only rows that contain the search terms. The idea would be to select only rows with the string $search from the table lines开发者_JS百科 in the column "Text". How could I do it? Thanks


$query = "SELECT * FROM lines WHERE Text LIKE '%".$search."%'";

Using mysql's LIKE combined with wildcards(%) should do the trick.


I don't recommend to use LIKE to solve substring or keyword searches, because that forces a table scan and cannot be improved by an index. Which means as your table grows, it will run hundreds or thousands of times slower than a solution using fulltext indexing.

MySQL supports a FULLTEXT index type, but it only works in MyISAM (currently). Read about how to CREATE FULLTEXT INDEX and how to use FULLTEXT index functions MATCH() AGAINST().

Most people use Sphinx Search or Apache Solr for fulltext indexing, as a complementary technology for MySQL.

See also my presentation Practical Full-Text Search in MySQL or my book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.


select * from lines where Text = $search

or use

select * from lines where Text like '%$search%' 

if you want to search for a value that includes $search but doesn't exactly match it.

EDIT

If $search only includes part of a value in Text but doesn't match the order of the words, I.E Text's value = "pizza in paris" and $search = "pizza paris", then you can split $search into separate strings and run a search with an and clause.

select * from lines where Text like '%$search1%' and Text like '%$search2%'

where $search1 is the first word and $search2 is the second word.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号