MySQL query LIKE %...% query returning other results? - mysql

So I'm trying to code a PHP script, but we'll just leave it at the SQL part of things since this is where the issue is arising. I've a SELECT * query which should only grab from the rows where the user ID matches, and the badge ID meets their userID followed by an underscore. Although, it's grabbing results that shouldn't be included?
Here's my SQL query:
SELECT *
FROM `user_badges`
WHERE `user_id` = 1
AND `badge_id` LIKE '%1_%'
That should only return badges that start/contain 1_, it is grabbing all the badges that do contain/start with 1_ but it's also grabbing it215. If I search a different user ID, for example my own, it will grab all the badges with 3_ AND it's also grabbing ACH_RoomDecoFurniCount31 which is confusing because it doesn't contain 3_. Maybe there's more to it? Could someone please point me in the right direction.

You need to escape the _ as it's a wildcard character. Your query would should be like this:
SELECT *
FROM `user_badges`
WHERE `user_id` = 1
AND `badge_id` LIKE '%1\_%'

_ is also a wildcard in SQL - A substitute for a single character

_ is also a wildcard character. It means "any single character" (whereas % is "any sequence of characters").
You could escape/quote that _ or use the LOCATE function instead of a pattern match.
WHERE badge_id LIKE '%1\_%'
WHERE locate('1_', badge_id) > 0

_ is a wildcard "_ matches exactly one character." so what you are saying is:
% : starts with anything(or nothing)
1: contains 1
_: has exactly 1 of % (or anything, or nothing)
http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

Related

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

MySQL different counts between "where =" and "where like"

1. select count(*) from tableX where code = "XYZ";
2. select count(*) from tableX where code like "%XYZ";
Result for query 1 is 18734. <== Not Correct
Result for query 2 is 93003. <== Correct
We know that query 2's count is correct based on independent verification.
We expect these two queries to have the exact same count for each because we know that no rows in tableX have a code that ends with "XYZ", so the wildcard at the beginning shouldn't affect the query.
Why would these queries produce different counts?
We have already researched the differences between "=" comparison and "like" string comparison, but based on all our verification checks, we still don't understand why this would give us different counts
We have confirmed the following:
There are no leading or trailing characters in the "code" field
There are no hidden characters (tried all found here: How can I find non-ASCII characters in MySQL?)
The collation is "utf8_unicode_ci"
We are using MySQL version 5.5.40-0ubuntu0.12.04.1.
Try this in order to get your answer:
SELECT code
FROM tableX
WHERE code LIKE "%XYZ"
AND code <> "XYZ"
LIMIT 10
My guess is that some of your codes end with a lowercase xyz, and since LIKE is case-insensitive, it matched these where = did not.
where code = "XYZ"; gives exact match whereas where code LIKE "%XYZ"; includes partial match as well. In your case, there could be an extra space present which is giving wrong count. Consider trimming before comparing like
where UPPER(TRIM(code)) = 'XYZ';
We restarted the server that the database resides on, we re-ran the queries, and now they all are producing the expected, correct results...
We'll have to look into possibilities for why this "fixed" the issue.

LIKE MySQL search not functioning with CONCAT

I got a problem regarding SQL query. If single word SQL query can detect the string, but if I add multiple words inside the string, it won't show any results.
SELECT * FROM rules WHERE keyword LIKE CONCAT('%','$message','%')
Input 1 (show results)
$message = "ASK"
Input 2 (show no results)
$message = "I WANT TO ASK"
I'm assuming you want those rows where the value of the keyword column is part of the message. That's the typical use case for key words.
If that's right then you've get this result with the help of the function INSTR:
SELECT * FROM rules WHERE INSTR('$message', keyword) > 0;
While
SELECT * FROM rules WHERE '$message' LIKE CONCAT('%', keyword, '%');
would work most times too, it's got the restriction that the keyword musn't contain the wildcard characters for the LIKE operator: % and _. INSTR doesn't have this restriction.

Select all from DB where the content has defined

I am trying to retrieve a list of database records which have specific 'interest codes' inside of the 'custom_fields' table. So for example right now there is 100 records, I need the Name, Email and Interest Code from each of those records.
I've tried with the following statement:
SELECT * FROM `subscribers` WHERE list = '27' AND custom_fields LIKE 'CV'
But with no luck, the response was:
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0003 sec )
You can see in this screenshot that at-least two rows have 'CV' inside custom_fields. Whilst within the database it's not called 'Interest Code', that's what they are so therefore why I am referencing it in this way.
You need to enclose your "search string" inside some wildcards:
select * from subscribers where list=27 and custom_fields like '%CV%';
The % wildcard means "zero or more chacarcters at this position". The "_" wildcard means "a character in this position". Please read the reference manual on the topic. Also, you may want to read about regular expressions in MySQL for more complex string comparissons.

MySQL query - select postcode matches

I need to make a selection based on the first 2 characters of a field, so for example
SELECT * from table WHERE postcode LIKE 'rh%'
But this would select any record that contains those 2 characters at any point in the "postcode" field right? I am in need of a query that just selects the first 2 characters. Any pointerS?
Thanks
Your query is correct. It searches for postcodes starting with "rh".
In contrast, if you wanted to search for postcodes containing the string "rh" anywhere in the field, you would write:
SELECT * from table WHERE postcode LIKE '%rh%'
Edit:
To answer your comment, you can use either or both % and _ for relatively simple searches. As you have noticed already, % matches any number of characters whereas _ matches a single character.
So, in order to match postcodes starting with "RHx " (where x is any character) your query would be:
SELECT * from table WHERE postcode LIKE 'RH_ %'
(mind the space after _). For more complex search patterns, you need to read about regular expressions.
Further reading:
http://dev.mysql.com/doc/refman/5.1/en/pattern-matching.html
http://dev.mysql.com/doc/refman/5.1/en/regexp.html
LIKE '%rh%' will return all rows with 'rh' anywhere
LIKE 'rh%' will return all rows with 'rh' at the beginning
LIKE '%rh' will return all rows with 'rh' at the end.
If you want to get only first two characters 'rh', use MySQL SUBSTR() function
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substr
Dave, your way seems correct to me (and works on my test data). Using a leading % as well will match anywhere in the string which obviously isn't desirable when dealing with postcodes.