乐闻世界logo
搜索文章和话题

How do you use the LIKE operator in MySQL?

1个答案

1

In MySQL, the LIKE operator is primarily used for fuzzy matching in the WHERE clause to match specific patterns within columns. When using the LIKE operator, it is common to combine the % wildcard (representing any number of characters) and the _ wildcard (representing a single character) to define patterns.

Basic Syntax

sql
SELECT column1, column2, ... FROM table_name WHERE columnN LIKE pattern;

Example

Assume we have a database table Employees with the following structure:

EmployeeIDFirstNameLastName
1AliceSmith
2BobJohnson
3CharlieBrown
4DavidLee
5EveArnold

Example 1: Using the % Wildcard

To find all employees whose last names end with "n", use the following SQL query:

sql
SELECT * FROM Employees WHERE LastName LIKE '%n';

This will return:

EmployeeIDFirstNameLastName
2BobJohnson
3CharlieBrown

Example 2: Using the _ Wildcard

To find all employees whose first names have 'a' as the second letter, use the following SQL query:

sql
SELECT * FROM Employees WHERE FirstName LIKE '_a%';

This will return:

EmployeeIDFirstNameLastName
3CharlieBrown
4DavidLee

Notes

  • The search is case-sensitive when using LIKE.
  • The % and _ wildcards can be used anywhere in the pattern and can be used multiple times.

As demonstrated by the examples above, the LIKE operator is highly useful for performing fuzzy matching queries.

2024年8月6日 22:32 回复

你的答案