Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT query string matching

Normally, when querying a database with SELECT, its common to want to find the records that match a given search string.

For example:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%'; 

That query should give me all records where 'Bob Smith' appears anywhere in the name field.

What I'd like to do is the opposite.

Instead of finding all the records that have 'Bob Smith' in the name field, I want to find all the records where the name field is in 'Robert Bob Smith III, PhD.', a string argument to the query.

like image 297
JR Lawhorne Avatar asked Feb 06 '11 21:02

JR Lawhorne


People also ask

How do I match a string in MySQL?

STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one.

How do I match part of a string in SQL?

SQL Pattern Matching : It is used for searching a string or a sub-string to find certain character or group of characters from a string. We can use LIKE Operator of SQL to search sub-string. The LIKE operator is used with the WHERE Clause to search a pattern in string of column.

How do I match data in MySQL?

Example - Equality Operator In MySQL, you can use the = operator to test for equality in a query. The = operator can only test equality with values that are not NULL. For example: SELECT * FROM contacts WHERE last_name = 'Johnson';

How do you check if a substring is present in a string in MySQL?

The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search. Note: This function is equal to the POSITION() function.


1 Answers

Just turn the LIKE around

SELECT * FROM customers WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%') 
like image 109
The Scrum Meister Avatar answered Oct 04 '22 10:10

The Scrum Meister