Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL starts with searching issue

I'm having an issue using the % wildcard with a MySQL query.

http://www.w3schools.com/sql/sql_like.asp

Having read that article, I am using % and not getting quite what I was expecting.

I have a series of values, such as

1_1 1_2 2_1 2_2... etc 

including

11_1 11_2 

Now, in some cases I want to return specifically those whose value = 11_2, or 1_2 etc. This works fine

WHERE fieldName = '11_2' 

etc... as expected

However, in some cases I want to find all items which start with a 1 or all items which start with 11

From the w3Schools link, I was expecting

WHERE fieldName LIKE '1_%' 

To find anything that begins with 1_ specifically, therefore, in my example, returning:

1_1 1_2 

BUT, it also returns

11_1 11_2 

Why is this? And how can I over come it?

like image 766
Jamie Hartnoll Avatar asked Mar 07 '12 17:03

Jamie Hartnoll


People also ask

How do you check if a string starts with a letter in MySQL?

Show activity on this post. In MySQL use the '^' to identify you want to check the first char of the string then define the array [] of letters you want to check for. REGEXP is a synonym for RLIKE so this answer is the same as the one given by @ZenOut.

How do you select a name starting with a vowel in SQL?

To check if a name begins ends with a vowel we use the string functions to pick the first and last characters and check if they were matching with vowels using in where the condition of the query. We use the LEFT() and RIGHT() functions of the string in SQL to check the first and last characters.

What is search query in MySQL?

Full-Text Search in MySQL server lets users run full-text queries against character-based data in MySQL tables. You must create a full-text index on the table before you run full-text queries on a table. The full-text index can include one or more character-based columns in the table.


1 Answers

Underscore is a wildcard for a single character. You will need to change your SQL to something like:

WHERE fieldName LIKE '1%' 

Or you can escape the underscore

WHERE fieldName LIKE '1\_%'  
like image 194
markblandford Avatar answered Sep 19 '22 06:09

markblandford