Оператор MySQL LIKE
Оператор MySQL LIKE проверяет, соответствует ли конкретная символьная строка указанному шаблону.
expr LIKE pat [ESCAPE 'escape_char']
- Сопоставление с образцом с использованием простого сравнения регулярных выражений SQL. Возвращает 1 (ИСТИНА) или 0 (ЛОЖЬ). Если expr или pat имеют значение NULL, результат равен NULL.
- Шаблон не обязательно должен быть литеральной строкой. Например, его можно указать как строковое выражение или столбец таблицы.
- В соответствии со стандартом SQL, LIKE выполняет сопоставление для каждого символа, поэтому он может давать результаты, отличные от оператора сравнения =.
- Оператор LIKE использует WILDCARDS (то есть%, _) для сопоставления с шаблоном. Это очень полезно для проверки наличия в записях определенного символа или строки.
% используется для соответствия любому количеству символов, даже нулю символов.
_ используется для соответствия ровно одному символу.
Чтобы проверить наличие буквенных символов подстановочного знака, перед ним должен быть escape-символ. Если вы не укажете символ ESCAPE, подразумевается «/».
/% используется для соответствия одному символу «%».
/ _ Соответствует одному символу «_»
Версия MySQL: 5.6
Пример: оператор MySQL LIKE
Следующая инструкция MySQL сканирует всю таблицу авторов, чтобы найти любое имя автора, имя которого начинается с символа «W», за которым следуют любые символы.
SELECT aut_name, country FROM author WHERE aut_name LIKE 'W%';
mysql> mysql> SELECT aut_name, страна -> ОТ автора -> ГДЕ aut_name LIKE 'W%'; + ----------------- + --------- + | aut_name | страна | + ----------------- + --------- + | Уильям Нортон | Великобритания | | Уильям Моэм | Канада | | Уильям Энтони | Великобритания | + ----------------- + --------- + 3 ряда в наборе (0,05 сек)
List of authors whose name starts with 'w', along with their country:
Publisher Country query('SELECT aut_name, country FROM author WHERE aut_name LIKE "W%"') as $row) < echo ""; echo "" . $row['aut_name'] . " "; echo "" . $row['country'] . " "; echo " "; > ?>
Publisher Country %> catch (Exception ex) < out.println("Can’t connect to database."); >%>
Пример: оператор MySQL LIKE, соответствующий концу
Следующая инструкция MySQL сканирует всю таблицу авторов, чтобы найти любого автора, имя которого заканчивается строкой ‘on’.
SELECT aut_name, country FROM author WHERE aut_name LIKE '%on';
mysql> SELECT aut_name, страна -> ОТ автора -> ГДЕ aut_name LIKE '% on'; + ---------------- + --------- + | aut_name | страна | + ---------------- + --------- + | Уильям Нортон | Великобритания | | Томас Мертон | США | | Пирс Гибсон | Великобритания | | Джозеф Мильтон | США | + ---------------- + --------- + 4 ряда в наборе (0,00 сек)
Пример: оператор MySQL LIKE, соответствующий строке
Следующая инструкция MySQL сканирует всю таблицу авторов, чтобы найти любого автора, в имени которого есть строка «an». Имя автора хранится в столбце aut_name.
SELECT aut_name, country FROM author WHERE aut_name LIKE '%an%';
mysql> SELECT aut_name, страна -> ОТ автора -> ГДЕ aut_name LIKE '% an%'; + ---------------------- + ----------- + | aut_name | страна | + ---------------------- + ----------- + | Уильям Энтони | Великобритания | | С.Б.Сваминатан | Индия | | Томас Морган | Германия | | Джон Бежеман Хантер | Австралия | | Эван Хайек | Канада | | Батлер Андре | США | + ---------------------- + ----------- + 6 рядов в наборе (0,00 сек)
Пример: оператор MySQL LIKE, соответствующий указанной строке
Следующее утверждение MySQL ищет всех авторов, чьи родные города, такие как «Лондон», «Лэндон» и т. Д., Подстановочный знак подчеркивания используется для упоминания одного символа.
SELECT aut_name, country,home_city FROM author WHERE home_city LIKE 'L_n_on';
mysql> ВЫБРАТЬ aut_name, страну, home_city -> ОТ автора -> ГДЕ home_city LIKE 'L_n_on'; + -------------- + --------- + ----------- + | aut_name | страна | home_city | + -------------- + --------- + ----------- + | Пирс Гибсон | Великобритания | Лондон | | Си Джей Уайльд | Великобритания | Лондон | + -------------- + --------- + ----------- + 2 ряда в наборе (0,00 сек)
Пример: оператор MySQL LIKE, соответствующий управляющему символу
Для поиска символа подстановки или комбинации символа подстановки и любого другого символа символу подстановки должен предшествовать строка ESCAPE. В MySQL строка ESCAPE по умолчанию — «/». Следующая инструкция MySQL возвращает те записи, чьи isbn_no содержат «_16».
SELECT book_name,isbn_no,no_page,book_price FROM book_mast WHERE isbn_no LIKE '%\_16%';
mysql> SELECT book_name, isbn_no, no_page, book_price -> ОТ book_mast -> ГДЕ isbn_no НРАВИТСЯ "% / _ 16%"; + --------------------------------- + ------------- + - -------- + ------------ + | book_name | isbn_no | no_page | book_price | + --------------------------------- + ------------- + - -------- + ------------ + | Сети и Телекоммуникации | 00009790_16 | 95 | 45,00 | + --------------------------------- + ------------- + - -------- + ------------ + 1 ряд в наборе (0,00 сек)
Пример: оператор MySQL LIKE, соответствующий начальной и конечной строке
Подстановочные знаки также можно использовать в середине шаблона поиска. Следующая инструкция MySQL найдет всех авторов, чьи имена начинаются с ‘t’ и заканчиваются на ‘n’.
SELECT aut_name, country FROM author WHERE aut_name LIKE 't%n';
mysql> SELECT aut_name, страна -> ОТ автора -> ГДЕ aut_name LIKE 't% n'; + --------------- + --------- + | aut_name | страна | + --------------- + --------- + | Томас Морган | Германия | | Томас Мертон | США | + --------------- + --------- + 2 ряда в наборе (0,00 сек)
Слайд-шоу функции сравнения MySQL и операторов
Предыдущий: Меньше чем оператор ( <)
Далее: НЕ МЕЖДУ И
MySQL — LIKE Clause
We have seen the SQL SELECT command to fetch data from the MySQL table. We can also use a conditional clause called as the WHERE clause to select the required records.
A WHERE clause with the ‘equal to’ sign (=) works fine where we want to do an exact match. Like if «tutorial_author = ‘Sanjay'». But there may be a requirement where we want to filter out all the results where tutorial_author name should contain «jay». This can be handled using SQL LIKE Clause along with the WHERE clause.
If the SQL LIKE clause is used along with the % character, then it will work like a meta character (*) as in UNIX, while listing out all the files or directories at the command prompt. Without a % character, the LIKE clause is very same as the equal to sign along with the WHERE clause.
Syntax
The following code block has a generic SQL syntax of the SELECT command along with the LIKE clause to fetch data from a MySQL table.
SELECT field1, field2. fieldN table_name1, table_name2. WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'
- You can specify any condition using the WHERE clause.
- You can use the LIKE clause along with the WHERE clause.
- You can use the LIKE clause in place of the equals to sign.
- When LIKE is used along with % sign then it will work like a meta character search.
- You can specify more than one condition using AND or OR operators.
- A WHERE. LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.
Using the LIKE clause at the Command Prompt
This will use the SQL SELECT command with the WHERE. LIKE clause to fetch the selected data from the MySQL table – tutorials_tbl.
Example
The following example will return all the records from the tutorials_tbl table for which the author name ends with jay −
root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl -> WHERE tutorial_author LIKE '%jay'; +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 1 rows in set (0.01 sec) mysql>
Using LIKE clause inside PHP Script
PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using Like clause. This function takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
Required — SQL query to select records in a MySQL table using Like Clause.
Optional — Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Example
Try the following example to select a record using like clause in a table −
Copy and paste the following example as mysql_example.php −
connect_errno ) < printf("Connect failed: %s
", $mysqli->connect_error); exit(); > printf('Connected successfully.
'); $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author like "Mah%"'; $result = $mysqli->query($sql); if ($result->num_rows > 0) < while($row = $result->fetch_assoc()) < printf("Id: %s, Title: %s, Author: %s, Date: %d
", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); > > else < printf('No record found.
'); > mysqli_free_result($result); $mysqli->close(); ?>
Output
Access the mysql_example.php deployed on apache web server and verify the output. Here we’ve entered multiple records in the table before running the select script.
Connected successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
PDO LIKE
Summary: in this tutorial, you’ll learn how to use PDO to execute a query with the LIKE operator.
Introduction to the SQL LIKE operator
The LIKE operator returns true if a character string matches a specified pattern. Typically, a pattern includes wildcard characters like:
For example, the %er% will match any string that contains the string er , e.g., peter , understand , etc.
Typically, you use the LIKE operator in the WHERE clause of the SELECT , UPDATE , and DELETE statement.
Execute a query that contains the LIKE operator in PDO
To execute a query that contains a LIKE operator in PDO, you need to construct the pattern upfront.
For example, to select the book with titles that contain the string ‘es, you first construct a SELECT statement like this:
$sql = 'SELECT book_id, title FROM books WHERE title LIKE :pattern';
Code language: PHP (php)
And then bind the string ‘%es%’ to the prepared statement.
The following example illustrates how to execute a query that includes the LIKE operator:
/** * Find books by title based on a pattern */ function find_book_by_title(\PDO $pdo, string $keyword): array < $pattern = '%' . $keyword . '%'; $sql = 'SELECT book_id, title FROM books WHERE title LIKE :pattern'; $statement = $pdo->prepare($sql); $statement->execute([':pattern' => $pattern]); return $statement->fetchAll(PDO::FETCH_ASSOC); > // connect to the database $pdo = require 'connect.php'; // find books with the title matches 'es' $books = find_book_by_title($pdo, 'es'); foreach ($books as $book) < echo $book['title'] . '
'; >
Code language: PHP (php)
The function find_book_by_title() returns the books with the title that matches with the $keyword .
First, make the pattern by adding the wildcard characters to the beginning and end of the $keyword :
$pattern = '%' . $keyword . '%';
Code language: PHP (php)
Second, construct an SQL statement that contains a LIKE operator in the WHERE clause:
$sql = 'SELECT book_id, title FROM books WHERE title LIKE :pattern';
Code language: PHP (php)
Third, create a prepared statement:
$statement = $pdo->prepare($sql);
Code language: PHP (php)
After that, execute the statement with the value that comes from the pattern:
$statement->execute([':pattern' => $pattern]);
Code language: PHP (php)
Finally, return all rows from the result set by using the fetchAll() method:
return $statement->fetchAll(PDO::FETCH_ASSOC);
Code language: PHP (php)
The following code find books with the title contains the keyword ‘es’ :
// connect to the database $pdo = require 'connect.php'; // find books with the title matches 'es' $books = find_book_by_title($pdo, 'es'); foreach ($books as $book) < echo $book['title'] . '
'; >
Code language: PHP (php)
Marcus Makes a Movie Box of Butterflies
Code language: PHP (php)