example-not-like — php mysql examples | w3resource

Как работают операторы SQL LIKE и NOT LIKE

Оператор SQL LIKE используется вместе с WHERE для поиска шаблона для столбца. Подстановочные знаки помогут вам определить требуемый шаблон. Два подстановочных знака, которые используются с оператором LIKE:

  1. %: символ процента используется для представления одного или нескольких вхождений, а также для определения их отсутствия.
  2. _: подчеркивание используется для представления одного символа.

Чтобы использовать оператор 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 Expression: MySQL NOT LIKE operator with (%) percent.

Relational Algebra Tree:

Relational Algebra Tree: MySQL NOT LIKE operator with (%) percent.

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)
         
query('SELECT aut_name, country FROM author WHERE aut_name NOT LIKE "W%"') as $row) < echo ""; echo ""; echo ""; echo ""; > ?>
AuthorsCountry
" . $row['aut_name'] . "" . $row['country'] . "
            Authors Country     %> catch (Exception ex) < out.println("Can’t connect to database."); >%>   

Example : MySQL NOT LIKE operator with ( _ ) underscore

The following MySQL statement excludes those rows from the table author having the country name like the above pattern as specified with LIKE operator.

SELECT aut_name, country,home_city FROM author WHERE country NOT LIKE 'U_A' and country NOT LIKE 'C__a_a'; 

Relational Algebra Expression:

Relational Algebra Expression: MySQL NOT LIKE operator with ( _ ) underscore.

Relational Algebra Tree:

Relational Algebra Tree: MySQL NOT LIKE operator with ( _ ) underscore.

Sample table: author

Sample Output:

mysql> SELECT aut_name, country,home_city -> FROM author -> WHERE country NOT LIKE 'U_A' and country NOT LIKE 'C__a_a'; +----------------------+-----------+----------------+ | aut_name | country | home_city | +----------------------+-----------+----------------+ | William Norton | UK | Cambridge | | William Anthony | UK | Leeds | | S.B.Swaminathan | India | Bangalore | | Thomas Morgan | Germany | Arnsberg | | Piers Gibson | UK | London | | Marquis de Ellis | Brazil | Rio De Janerio | | John Betjeman Hunter | Australia | Sydney | | E. Howard | Australia | Adelaide | | C. J. Wilde | UK | London | +----------------------+-----------+----------------+ 9 rows in set (0.00 sec)
         
query('SELECT aut_name, country,home_city FROM author WHERE country NOT LIKE "U_A" and country NOT LIKE "C__a_a"') as $row) < echo ""; echo ""; echo ""; echo ""; echo ""; > ?>
AuthorsCountryHome city
" . $row['aut_name'] . "" . $row['country'] . "" . $row['home_city'] . "

Online Practice Editor:

Slideshow of MySQL Comparison Function and Operators

MySQL Comparison Function and Operators, slide presentation

Follow us on Facebook and Twitter for latest update.

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

MySQL not like operator

MySQL NOT LIKE operator along with WILDCARDS checks whether a string of a specified pattern is not present within another string.

This function is useful in —

MySQL Version: 8.0

Example of MySQL not like operator with wildcard ( _ ) underscore

SELECT * FROM author WHERE aut_name NOT LIKE '_______________'; 

Relational Algebra Expression:

Relational Algebra Expression: MySQL not like operator with wildcard ( _ ) underscore.

Relational Algebra Tree:

Relational Algebra Tree: MySQL not like operator with wildcard ( _ ) underscore.

Explanation:

The above MySQL statement will return those rows from the table author in which the length of the author’s name is not exactly 15 characters. Fifteen instances of ‘_’ pattern character has been used to indicate 15 characters.

mysql> SELECT * FROM author -> WHERE aut_name NOT LIKE '_______________'; +--------+----------------------+-----------+----------------+ | aut_id | aut_name | country | home_city | +--------+----------------------+-----------+----------------+ | AUT001 | William Norton | UK | Cambridge | | AUT005 | Thomas Morgan | Germany | Arnsberg | | AUT006 | Thomas Merton | USA | New York | | AUT007 | Piers Gibson | UK | London | | AUT008 | Nikolai Dewey | USA | Atlanta | | AUT009 | Marquis de Ellis | Brazil | Rio De Janerio | | AUT010 | Joseph Milton | USA | Houston | | AUT011 | John Betjeman Hunter | Australia | Sydney | | AUT012 | Evan Hayek | Canada | Vancouver | | AUT013 | E. Howard | Australia | Adelaide | | AUT014 | C. J. Wilde | UK | London | | AUT015 | Butler Andre | USA | Florida | +--------+----------------------+-----------+----------------+ 12 rows in set (0.00 sec)

Example of MySQL not like operator with wildcard (%)

SELECT * FROM author WHERE aut_name NOT LIKE '%t%'; 

Relational Algebra Expression:

Relational Algebra Expression: MySQL not like operator with wildcard (%).

Relational Algebra Tree:

Relational Algebra Tree: MySQL not like operator with wildcard (%).

Explanation:

The above MySQL statement will return those rows from the table author in which the author’s name does not containing a character ‘t’.

mysql> SELECT * FROM author -> WHERE aut_name NOT LIKE '%t%'; +--------+------------------+-----------+----------------+ | aut_id | aut_name | country | home_city | +--------+------------------+-----------+----------------+ | AUT002 | William Maugham | Canada | Toronto | | AUT007 | Piers Gibson | UK | London | | AUT008 | Nikolai Dewey | USA | Atlanta | | AUT009 | Marquis de Ellis | Brazil | Rio De Janerio | | AUT012 | Evan Hayek | Canada | Vancouver | | AUT013 | E. Howard | Australia | Adelaide | | AUT014 | C. J. Wilde | UK | London | +--------+------------------+-----------+----------------+ 7 rows in set (0.00 sec)

Video Presentation:

Your browser does not support HTML5 video.

Previous: MID
Next: NOT REGEXP

Follow us on Facebook and Twitter for latest update.

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Читайте также:  Javascript and mysql query
Оцените статью