Как работают операторы SQL LIKE и NOT LIKE
Оператор SQL LIKE используется вместе с WHERE для поиска шаблона для столбца. Подстановочные знаки помогут вам определить требуемый шаблон. Два подстановочных знака, которые используются с оператором LIKE:
- %: символ процента используется для представления одного или нескольких вхождений, а также для определения их отсутствия.
- _: подчеркивание используется для представления одного символа.
Чтобы использовать оператор SQL LIKE, вы должны быть уверены в использовании позиции подстановочного знака, поскольку он будет определять шаблон поиска.
Синтаксис оператора SQL LIKE
Оператор SQL LIKE можно использовать с любым запросом вместе с where. Таким образом, мы можем использовать его с Select, Delete, Update и т. д.
SELECT column FROM table_name WHERE column LIKE pattern; UPDATE table_name SET column=value WHERE column LIKE pattern; DELETE FROM table_name WHERE column LIKE pattern;
В упомянутом выше синтаксисе оператора LIKE шаблон определяется использованием подстановочных знаков.
Примеры использования оператора SQL LIKE
Давайте попробуем понять, как работает оператор SQL LIKE вместе с подстановочными знаками, на некоторых примерах. В качестве примера рассмотрим следующую таблицу Customer.
CustomerId | CustomerName |
1 | Amit |
2 | John |
3 | Annie |
И попробуем выполнить пару практичных примеров. Допустим, мы хотим найти имя клиента, которое начинается на А:
SELECT CustomerName FROM Customer WHERE CustomerName LIKE 'A%';
Найдем клиента, имя которого оканчивается на «е».
SELECT CustomerName FROM Customer WHERE CustomerName LIKE '%e'
Найдем теперь клиента, имя которого начинается с «А» и заканчивается на «т».
SELECT CustomerName FROM Customer WHERE CustomerName LIKE 'A%t'
Давайте найдем клиента с именем, содержащим символ «n» в любой позиции.
SELECT CustomerName FROM Customer WHERE CustomerName LIKE '%n%'
Чтобы найти клиента, вторым символом в имени которого является n, введите:
SELECT CustomerName FROM Customer WHERE CustomerName LIKE '_n%'
Давайте теперь найдем клиента, третьим символом в имени которого является i, а последним – t.
SELECT CustomerName FROM Customer WHERE CustomerName LIKE '__i%t'
Оператор SQL NOT LIKE
Иногда мы хотим извлечь записи, которые не соответствуют определенному шаблону. В этом случае можно использовать оператор SQL NOT LIKE. Синтаксис оператора SQL NOT LIKE выглядит так:
SELECT column FROM table_name WHERE column NOT LIKE pattern; UPDATE table_name SET column=value WHERE column NOT LIKE pattern; DELETE FROM table_name WHERE column NOT LIKE pattern;
Ради примера предположим, что нам нужно извлечь список имен клиентов, которые не начинаются с буквы «А». Ниже представлен запрос, который даст нам требуемый набор результатов.
SELECT CustomerName FROM Customer WHERE CustomerName NOT LIKE 'A%';
Множественный оператор SQL LIKE
Мы можем использовать несколько операторов LIKE в одном SQL-запросе. Например, если нам нужен список имен клиентов, начинающихся с Jo и Am, нам придется использовать несколько операторов LIKE, как показано ниже.
SELECT CustomerName FROM Customer WHERE CustomerName LIKE 'Am%' OR CustomerName LIKE 'Jo%';
MySQL NOT LIKE operator
MySQL NOT LIKE is used to exclude those rows which are matching the criterion followed by LIKE operator.
expr NOT LIKE pat [ESCAPE 'escape_char']
- Pattern matching using SQL simple regular expression comparison. Returns 1 (TRUE) or 0 (FALSE). If either expr or pat is NULL, the result is NULL.
- The pattern need not be a literal string. For example, it can be specified as a string expression or table column.
- Per the SQL standard, LIKE performs matching on a per-character basis, thus it can produce results different from the = comparison operator.
- LIKE operator uses WILDCARDS (i.e. %, _) to match the pattern. This is very useful to check whether a particular character or string is present in the records.
% is used to match any number of characters, even zero characters.
_ is used to match exactly one character.
To test for literal instances of a wildcard character, precede it by the escape character. If you do not specify the ESCAPE character, “\” is assumed.
\% is used to match one «%» character.
\_ Matches one «_» character
MySQL Version: 5.6
Example: MySQL NOT LIKE operator with (%) percent
The following MySQL statement excludes those rows from the table author, having the 1st character of aut_name ‘W’.
SELECT aut_name, country FROM author WHERE aut_name NOT LIKE 'W%';
Relational Algebra Expression:
Relational Algebra Tree:
Sample table: author
Sample Output:
mysql> SELECT aut_name, country -> FROM author -> WHERE aut_name NOT LIKE 'W%'; +----------------------+-----------+ | aut_name | country | +----------------------+-----------+ | S.B.Swaminathan | India | | Thomas Morgan | Germany | | Thomas Merton | USA | | Piers Gibson | UK | | Nikolai Dewey | USA | | Marquis de Ellis | Brazil | | Joseph Milton | USA | | John Betjeman Hunter | Australia | | Evan Hayek | Canada | | E. Howard | Australia | | C. J. Wilde | UK | | Butler Andre | USA | +----------------------+-----------+ 12 rows in set (0.00 sec)
Authors Country query('SELECT aut_name, country FROM author WHERE aut_name NOT LIKE "W%"') as $row) < echo ""; echo "" . $row['aut_name'] . " "; echo "" . $row['country'] . " "; echo " "; > ?>