How do I use WHERE LIKE properly in a mysql prepared statement? - mysql

I'm trying to puzzle out how to add a LIKE to this prepared statement.
SELECT convention_name FROM events_master
WHERE (convention_name = ?);
The goal is to see if the convention name is similar to something that already exists in convention_name. I do understand that it checks for an exact match already.
Thanks in advance.

SELECT convention_name FROM events_master
WHERE (convention_name LIKE 'partofname' + '%');
The % character is a wild char so if you put it in the back it will search for anything that begins with 'partofname' + blah appended to it.
if it's Like = '%partofname%' then partofname could have characters before or after it.

If SQL LIKE clause is used along with % characters, then it will work
like a meta character (*) in UNIX while listing out all the files or
directories at command prompt.
Without a % character, LIKE clause is very similar to equals sign
along with WHERE clause.
$sql = $dbh->prepare(SELECT convention_name FROM events_master
WHERE convention_name LIKE ?");
$sql->execute(array('%'.$yourSearchString.'%'));

For example:
String query = "SELECT convention_name FROM events_master WHERE convention_name like ?";
PreparedStatement stm = conn.prepareStatement(query);
stm.setString(1, "%car%");
Your argument may contain wildchar %, then it will find for example card, scart ..
If this substring match is not enough, then you can use soundex algorithm to find similar strings. See how to compute similarity between two strings in MYSQL for more options.

Related

How to make mysql LIKE search for exactly single words only

I have a query like this:
SELECT * FROM mytable where description like %STRING%
The problem is: When I search for JAVAit returns me even the records with JAVAscript.
But, JAVA != JavaScript, right ? How can I work around it ?
MySQL's LIKE operator isn't really suitable to detect an exact single word inside a string. But REGEXP, which supports regular expressions, can handle this. Consider the following query:
SELECT * FROM mytable WHERE description REGEXP '[[:<:]]Java[[:>:]]';
This corresponds to matching the pattern \bJava\b, i.e. the word Java by itself.
Demo
Edit:
If you are trying to execute this query using Laravel, then whereRaw should come in handy:
$results = DB::table('mytable')
->whereRaw('description REGEXP ?', ['[[:<:]]Java[[:>:]]'])
->get();

MySQL underscore with LIKE Operator

I have an SQL query which matches results using a LIKE :
_column_name_%
This will return results where the column name is:
_column_name_1
_column_name_2
The end number could be a really high number e.g. 32523, or even 523624366234.
If I use _column_name_%%%%% this would match 32523, but not 523624366234.
How would I get the LIKE to match without typing % repeatedly?
A Simple select query with the LIKE operator should look like this
You have to escape the underscore using "\" if you are having any.
instead of pretext_% use pretext\_%
Select * from mytable where field_1 like 'pretext\_%'
This will return pretext_1 as well as pretext_11

Apostrophe in FULL TEXT SEARCH mysql

When I searched for citroen in search page like that I get result but if I search blackn roll I dont get result because it's written like black'n roll in the table. Some user may also wanna search blackn roll but doesnt get result. How can I fix it? And also rows like v-hr and speacial characters like "&/(). I want the mysql to ignore them.
$sql = "SELECT * FROM arac
INNER JOIN suv_marka ON arac.marka = suv_marka.id
WHERE match(suv_marka.marka) against('citroen')";
If you know the characters (to be replaced) already then, you can use MySQL's REPLACE function to replace them with % and perform LIKE comparison, e.g.:
create table test(value varchar(100));
insert into test values ('black''n roll');
SELECT value
FROM test
WHERE 'blackn roll' LIKE CONCAT('%', REPLACE(value, '''', '%'), '%');
You can replace 'blackn roll' with your input string and use nested REPLACE functions if you need to replace more than one character.
The back-slash is MySQL's escape character. You can try the following... Full text indexing gets a little weird because of word terminators.
$sql = "SELECT * FROM arac
INNER JOIN suv_marka ON arac.marka = suv_marka.id
WHERE match(suv_marka.marka) against ('black\'n roll' IN BOOLEAN MODE);"
If that doesn't work, then try looking for the words individually. Word length is also a factor, small words (less than 4 characters by default) are not indexed.
$sql = "SELECT * FROM arac
INNER JOIN suv_marka ON arac.marka = suv_marka.id
WHERE match(suv_marka.marka) against ('black' + 'roll' IN BOOLEAN MODE);"

mysql: replace \ (backslash) in strings

I am having the following problem:
I have a table T which has a column Name with names. The names have the following structure:
A\\B\C
You can create on yourself like this:
create table T ( Name varchar(10));
insert into T values ('A\\\\B\\C');
select * from T;
Now if I do this:
select Name from T where Name = 'A\\B\C';
That doesn't work, I need to escape the \ (backslash):
select Name from T where Name = 'A\\\\B\\C';
Fine.
But how do I do this automatically to a string Name?
Something like the following won't do it:
select replace('A\\B\C', '\\', '\\\\');
I get: A\\\BC
Any suggestions?
Many thanks in advance.
You have to use "verbatim string".After using that string your Replace function will
look like this
Replace(#"\", #"\\")
I hope it will help for you.
The literal A\\B\C must be coded as A\\\\A\\C, and the parameters of replace() need escaping too:
select 'A\\\\B\\C', replace('A\\\\B\\C', '\\', '\\\\');
output (see this running on SQLFiddle):
A\\B\C A\\\\B\\C
So there is little point in using replace. These two statements are equivalent:
select Name from T where Name = replace('A\\\\B\\C', '\\', '\\\\');
select Name from T where Name = 'A\\\\B\\C';
Usage of regular expression will solve your problem.
This below query will solve the given example.
1) S\\D\B
select * from T where Name REGEXP '[A-Z]\\\\\\\\[A-Z]\\\\[A-Z]$';
if incase the given example might have more then one char
2) D\\B\ACCC
select * from T where Name REGEXP '[A-Z]{1,5}\\\\\\\\[A-Z]{1,5}\\\\[A-Z]{1,5}$';
note: i have used 5 as the max occurrence of char considering the field size is 10 as its mentioned in the create table query.
We can still generalize it.If this still has not met your expectation feel free to ask for my help.
You're confusing what's IN the database with how you represent that data in SQL statements. When a string in the database contains a special character like \, you have to type \\ to represent that character, because \ is a special character in SQL syntax. You have to do this in INSERT statements, but you also have to do it in the parameters to the REPLACE function. There are never actually any double slashes in the data, they're just part of the UI.
Why do you think you need to double the slashes in the SQL expression? If you're typing queries, you should just double the slashes in your command line. If you're generating the query in a programming language, the best solution is to use prepared statements; the API will take care of proper encoding (prepared statements usually use a binary interface, which deals with the raw data). If, for some reason, you need to perform queries by constructing strings, the language should hopefully provide a function to escape the string. For instance, in PHP you would use mysqli_real_escape_string.
But you can't do it by SQL itself -- if you try to feed the non-escaped string to SQL, data is lost and it can't reconstruct it.
You could use LIKE:
SELECT NAME FROM T WHERE NAME LIKE '%\\\\%';
Not exactly sure by what you mean but, this should work.
select replace('A\\B\C', '\', '\\');
It's basically going to replace \ whereever encountered with \\ :)
Is this what you wanted?

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.