MySQL String pattern matching - Alternatives for like - mysql

MySQL like clause lets wildcard searches like '%keyword%' where keyword is sandwiched within the column value.
For pattern matching where the keyword contains a part of the column value and when %keyword% will not work, we can use INSTR function to do the search.
Example:
Column="Apple"
$keyword = "An Apple a day"
Here, we cannot do Column like '%$keyword%' to make a match but (INSTR('$Keyword', Column)>0 would do the match.
What alternatives (regex?, fulltext search?, lucene?) do we have other than INSTR for pattern-matching such cases (examples?) ?
Update:
Column = "Golden Apple"
$keyword = "An Apple a day"
Even for samples like this, I would like to be able to match the $keyword with column as they have a common term "Apple".

In this case, you can still use LIKE:
'%$keyword%' LIKE CONCAT('%', Column, '%')
Or regular expression:
'%$keyword%' REGEXP Column

I don't understand clearly what exactly you want to do, but try this link to find the help about pattern matching in mysql
Are you writing a procedure,a trigger, or simply a select?

Also consider SOUNDEX and Natural Language (using full text searches and relevance) searches.

Related

SQL Like query for each word containing keyword

E.g :
I have 1 word for search the data. And the word is 'ayam'.
And this is my query :
select nama_product from product where nama_product like %a%
It works fine. But it show the record that i dont want to be showed.
This is the result :
ayam bakar
daging ayam
bayam hijau
daun bayam
The first and the second result is okay. But the third and the last that i dont want to be showed.
Because i want to show 'ayam' not "b'ayam'"
How do i handle this? I don't know it is duplicate or not. Because i already search it but i didn't find.
If you need to search the word 'ayam' without any prefix and sufix character, you would better use regular expression for that .
e.g.,
SELECT namma_product FROM product WHERE namma_product REGEXP 'ayam'
try this. This will work
Unfortunately this is a limitation of SQL. Some SQL databases have advanced text searching functions such as regular expressions which allow very specific text results.
For your case you will likely have to perform multiple LIKE conditions. For example:
select nama_product
from product
where
nama_product like 'ayam %'
or nama_product like '% ayam %'
or nama_product like '% ayam'
or nama_product = 'ayam'
Please note that if the text fields are very large or if the table is large, queries that rely on LIKE operators can become very slow. LIKE does not scale well with large datasets. If this is a dataset you think will become very large in the future, best to design it in a way where the LIKE operator will not be needed.
You can use regex to match only whole words:
select nama_product
from product
where nama_product regexp '(^| )ayam( |$)';
(^| ) means the word must be the start of the string, or it must be preceded by a space
ayam is the word we're matching
( |$) means the word must be followed by a space, or it must be the end of the string
SQL Fiddle
when u insert '%' before and after it mean All Character before(after) your keyword so just change how u want
for example just keywords start with "ayam":
select nama_product from product where nama_product like 'ayam%'
another example just keywords ended with "ayam":
select nama_product from product where nama_product like '%ayam'
and after that look here ithink your answer is here :
Match only entire words with LIKE?

MySQL LIKE for two words

What would be the right SQL statement so that when I search two words, like for example 'text field' in a text box, it will return all results that has 'text' and 'field' in it using the LIKE statement?
I cant find the right terms to make a search.
EDIT : If possible, I want to make it dynamic. Like if a user search 5 words, all 5 words would be in the Like statement. I am trying to achieve a statement
SELECT * FROM table WHERE search (LIKE %searchterm1%) OR (LIKE %searchterm2%) OR (LIKE %searchterm3%) ....
The the words are unordered use a standard logical conjunction (aka AND)
LIKE '%word1%' AND LIKE '%word2%'
If the words are ordered use an implicit conjunction in the search term itself
LIKE '%word1%word2%'
Modify the like wildcards (and quotes) as needed; also consider if a full-text search might be more appropriate.
The correct syntax is;
SELECT * FROM table WHERE (column1 LIKE '%text%' AND column1 LIKE '%field%')
To allow the user to input multiple words, firstly take a look at the problems of SQL injection, but assuming you're using PHP you can explode an input string and implode the resulting array, like this;
$values = explode(" ", $input); // delimiter is a space
$query = "SELECT * FROM table WHERE (column1 LIKE '%" . implode("%' AND column1 LIKE '%",$values) . "%')";
Hope this helps!

MySQL String Comparison with Wildcards

I wrote a query where a user can input a string and get the data related to that string back from the database.
For example, a user will input Apple even though the full name is Apple Inc.
The code would be laid out as so...
and Description like '%Apple%'
The problem with this is, it will return Snapple along with Apple.
Aside from removing the first "%" wildcard and making the user type more, how can I limit the results to just Apple?
Use a regular expression:
WHERE Description RLIKE '[[:<:]]apple[[:>:]]'
[[:<:]] matches the beginning of a word, [[:>:]] matches the end of a word.
See the documentation for all the regexp operators supported by MySQL
Firstly - string comparison with wild cards (especially leading wild cards) doesn't really scale using "like". You might want to look at full-text searching instead. This basically gives you "google-like" text searching capabilities.
To answer your question, in most cases, "Apple" is a better match than "Snapple" for the term "apple". So, you could include the concept of "match quality" in the search - something like:
select *, 10 as MatchQuality
from table
where description like 'Apple'
union
select *, 5 as MatchQuality
from table
where description like 'Apple%'
union
select *, 1 as MatchQuality
from table
where description like '%Apple%'

SQL LIKE wildcard space character

let's say I have a string in which the words are separated by 1 or more spaces and I want to use that string in and SQL LIKE condition. How do I make my SQL and tell it to match 1 or more blank space character in my string? Is there an SQL wildcard that I can use to do that?
Let me know
If you're just looking to get anything with atleast one blank / whitespace then you can do something like the following WHERE myField LIKE '% %'
If your dialect allows it, use SIMILAR TO, which allows for more flexible matching, including the normal regular expression quantifiers '?', '*' and '+', with grouping indicated by '()'
where entry SIMILAR TO 'hello +there'
will match 'hello there' with any number of spaces between the two words.
I guess in MySQL this is
where entry RLIKE 'hello +there'
I know this is late, but I never found a solution to this in relation to a LIKE question.
There is no way to do what you're wanting within a SQL LIKE. What you would have to do is use REGEXP and [[:space:]] inside your expression.
So to find one or more spaces between two words..
WHERE col REGEXP 'firstword[[:space:]]+secondword'
Another way to match for one or more space would be to use [].
It's done like this.
LIKE '%[ ]%'
This will match one or more spaces.
you can't do this using LIKE but what you can do, if you know this condition can exist in your data, is as you're inserting the data into the table, use regular expression matching to detect it up front and set a flag in a different column created for this purpose.
I just replace the whitespace chars with '%'. Lets say I want to do a LIKE query on a string like this 'I want to query this string with a LIKE'
#search_string = 'I want to query this string with a LIKE'
#search_string = ("%"+#search_string+"%").tr(" ", "%")
#my_query = MyTable.find(:all, :conditions => ['my_column LIKE ?', #search_string])
first I add the '%' to the start and end of string with
("%"+#search_string+"%")
and then replace other remaining whitespace chars with '%' like so
.tr(" ", "%")
http://www.techonthenet.com/sql/like.php
The patterns that you can choose from are:
% allows you to match any string of any length (including zero length)
_ allows you to match on a single character
I think that the question is not asking to match any spaces but to match two strings one a pattern and the other with wrong number of spaces because of typos.
In my case I have to check two fields from different tables one preloaded and the other filled typed by users so sometimes they don't respect 100% the pattern.
The solution was to use LIKE in the join
Select table1.field
from table1
left join table2 on table1.field like('%' + replace(table2.field,' ','%')+'%')
if the condition:
WHERE myField LIKE '%Hello world%'
doesn't work try
WHERE myField LIKE '%Hello%'
and
WHERE myField LIKE '%world%'
this approach is helpful in a few specific use cases, hope this helps.

mysql query to match sentence against keywords in a field

I have a mysql table with a list of keywords such as:
id | keywords
---+--------------------------------
1 | apple, oranges, pears
2 | peaches, pineapples, tangerines
I'm trying to figure out how to query this table using an input string of:
John liked to eat apples
Is there a mysql query type that can query a field with a sentence and return results (in my example, record #1)?
One way to do it could be to convert apple, oranges, pears to apple|oranges|pears and use RLIKE (ie regular expression) to match against it.
For example, 'John liked to eat apples' matches the regex 'apple|orange|pears'.
First, to convert 'apple, oranges, pears' to the regex form, replace all ', ' by '|' using REPLACE. Then use RLIKE to select the keyword entries that match:
SELECT *
FROM keywords_table
WHERE 'John liked to eat apples' RLIKE REPLACE(keywords,', ','|');
However this does depend on your comma-separation being consistent (i.e. if there is one row that looks like apples,oranges this won't work as the REPLACE replaces a comma followed by a space (as per your example rows).
I also don't think it'll scale up very well.
And, if you have a sentence like 'John liked to eat pineapples', it would match both of the rows above (as it does have 'apple' in it). You could then try to add word boundaries to the regex (i.e. WHERE $sentence RLIKE '[[:<:]](apple|oranges|pears)[[:>:]]'), but this would screw up matching when you have plurals ('apples' wouldn't match '[wordboundary]apple[wordboundary]').
Hopefully this isn't more abstract than what you need but maybe good way of doing it.
I haven't tested this but I think it would work. If you can use PHP you can use str_replace to turn the spaces into keyword LIKE '%apple%'
$sentence = "John liked to eat apples";
$sqlversion = str_replace(" ","%' OR Keyword like '%",$sentence );
$finalsql = "%".$sqlversion."%";
the above will echo:
%John%' OR Keyword like '%liked%' OR Keyword like '%to%' OR Keyword like '%eat%' OR Keyword like '%apples%
Then just combine with your SQl statement
SQL ="SELECT *
FROM keywords_table
WHERE Keyword like" . $finalsql;
Storing comma delimited data is... less than ideal.
If you broke up the string "John liked to eat apples" into individual words, you could use the FIND_IN_SET operator:
WHERE FIND_IN_SET('apple', t.keywords) > 0
The performance wouldn't be great - this operation is better suited to Full Text Search.
I'm not aware of any direct solution to that type of query. But Full Text Search is a possibility. If you have a full-text index on the field of interest then a search with OR between each word in the sentence (although I think the OR operator is implied) would find that record ... but it might also find more than you want too.
I really don't think what you are looking for is completely possible but you can look into Full Text Search or SOUNDEX. SOUNDEX, for example, can do something like:
WHERE SOUNDEX(sentence) = SOUNDEX('%'+keywords+'%');
I have never tried it in this context but you should and let me know how it works out.