MySQL database replace and Regexp usage

Source: Internet
Author: User
Tags character classes

Replace and Regexp usage
0 comments | this entry was posted on Apr 08 2010.

MySQL replace usage
1. Replace
Replace into table (ID, name) values ('1', 'A'), ('2', 'bb ')
This statement inserts two records into the table. If the primary key ID is 1 or 2 does not exist
It is equivalent
Insert into table (ID, name) values ('1', 'A'), ('2', 'bb ')
Data is not inserted if the same value exists.

2. Replace (object, search, replace)
Replace all search objects with replace
Select Replace ('www .163.com ', 'w', 'ww')-> wwwwww.163.com
For example, replace AA in the Name field of the table with BB.
Update table set name = Replace (name, 'AA', 'bb ')
---------------------------

Other types of pattern matching provided by MySQL use extended regular expressions. When you perform a match test on this type of pattern, use the Regexp and not Regexp operators (or rlike and not rlike, which are synonyms ).

Some Characters of the extended regular expression are:

· '.' Matches any single character.

· The character class "[...]" matches any character in square brackets. For example, "[ABC]" matches "A", "B", or "C ". To name the character range, use a hyphen (-). "[A-Z]" matches any letter, and "[0-9]" matches any number.

· "*" Matches zero or multiple characters before it. For example, "x *" matches any number of "X" characters, "[0-9] *" matches any number, and ". * "matches any number of characters.

If the Regexp pattern matches any part of the tested value, the pattern matches (different from the like pattern match. The pattern matches only the entire value ).
To locate a pattern so that it must match the start or end of the tested value, use "^" at the start of the pattern or "$" at the end of the pattern ".
To demonstrate how the extended regular expression works, use Regexp to rewrite the like Query shown above:

To find the name starting with "B", use "^" to match the start of the name:

Mysql> select * From Pet where name Regexp '^ B ';
+ --- + -- + ---- +
| Name | Owner | species | sex | birth | death |
+ --- + -- + ---- +
| Buffy | Harold | dog | f | 1989-05-13 | null |
| Boane | Diane | dog | M |
+ --- + -- + ---- +
If you want to force Regexp to be case sensitive, use the binary keyword to convert a string to a binary string. This query only matches the lowercase 'B' of the first letter of the name '.

Mysql> select * From Pet where name Regexp binary '^ B ';
To find the name ending with "fy", use "$" to match the end Of the name:

Mysql> select * From Pet where name Regexp 'fy $ ';
+ --- + -- + ---- + --- +
| Name | Owner | species | sex | birth | death |
+ --- + -- + ---- + --- +
| Fluffy | Harold | cat | f | 1993-02-04 | null |
| Buffy | Harold | dog | f | 1989-05-13 | null |
+ --- + -- + ---- + --- +
To locate the name containing "W", use the following query:

Mysql> select * From Pet where name Regexp 'W ';
+ ---- + --- + -- + ---- +
| Name | Owner | species | sex | birth | death |
+ ---- + --- + -- + ---- +
| Claws | Gwen | cat | M | 1994-03-17 | null |
| Boane | Diane | dog | M |
| Whistler | Gwen | bird | null | 1997-12-09 | null |
+ ---- + --- + -- + ---- +
Since a regular expression appears anywhere in the value, its pattern matches, you do not have to place a wildcard on both sides of the pattern in the previous query so that it matches the entire value, just as if you were using an SQL mode.

To locate a name that contains exactly five characters, use "^" and "$" to match the start and end of the name, and the five "." instances are in the range:

Mysql> select * From Pet where name Regexp '^ ..... $ ';
+ --- + -- + ---- + --- +
| Name | Owner | species | sex | birth | death |
+ --- + -- + ---- + --- +
| Claws | Gwen | cat | M | 1994-03-17 | null |
| Buffy | Harold | dog | f | 1989-05-13 | null |
+ --- + -- + ---- + --- +
You can also use the "{n}" "Repeat n times" operator to overwrite the previous query:

Mysql> select * From Pet where name Regexp '^. {5} $ ';
+ --- + -- + ---- + --- +
| Name | Owner | species | sex | birth | death |
+ --- + -- + ---- + --- +
| Claws | Gwen | cat | M | 1994-03-17 | null |
| Buffy | Harold | dog | f | 1989-05-13 | null |
+ --- + -- + ---- + --- +
Appendix G: MySQL regular expressions provide detailed information about the syntax of regular expressions.

3.3.4.8. The counting row database is often used to answer this question: "How often does a type of data appear in a table ?" For example, you may want to know how many pets you have, how many pets each master has, or you may want to perform various types of surveys on your animals.
Calculate the total number of animals you own and the number of rows in the pet table ?" This is the same problem because each pet has a record. The count (*) function calculates the number of rows. Therefore, the query for the number of animals should be:

Mysql> select count (*) from PET;
+ ---- +
| Count (*) |
+ ---- +
| 9 |
+ ---- +
You have previously retrieved the name of a person with a pet. If you want to know how many pets each master has, you can use the count () function:

Mysql> select owner, count (*) from pet group by owner;
+ --- + ---- +
| Owner | count (*) |
+ --- + ---- +
| Benny | 2 |
| Diane | 2 |
| Gwen | 3 |
| Harold | 2 |
+ --- + ---- +
Note: If you use group by to group all records of each owner without it, you will receive an error message:

Mysql> select owner, count (*) from PET;
Error 1140 (42000): mixing of Group Columns (min (), max (), count (),...)
With no group columns is illegal if there is no group by clause
Count () and group by classify your data in various ways. The following example shows different methods for conducting an animal census.

Quantity of each animal:

Mysql> select species, count (*) from pet group by species;
+ --- + ---- +
| Species | count (*) |
+ --- + ---- +
| Bird | 2 |
| Cat | 2 |
| Dog | 3 |
| Hamster | 1 |
| Snake | 1 |
+ --- + ---- +
Number of animals for each gender:

Mysql> select sex, count (*) from pet group by sex;
+ -- + ---- +
| Sex | count (*) |
+ -- + ---- +
| Null | 1 |
| F | 4 |
| M | 4 |
+ -- + ---- +
(In this output, null indicates "unknown gender ".)

Number of animals by type and gender:

Mysql> select species, sex, count (*) from pet group by species, sex;
+ --- + -- + ---- +
| Species | sex | count (*) |
+ --- + -- + ---- +
| Bird | null | 1 |
| Bird | f | 1 |
| Cat | f | 1 |
| Cat | M | 1 |
| Dog | f | 1 |
| Dog | M | 2 |
| Hamster | f | 1 |
| Snake | M | 1 |
+ --- + -- + ---- +
If you use count (), you do not have to retrieve the entire table. For example, in the previous query, when only a dog or a cat is executed, it should be:

Mysql> select species, sex, count (*) from pet
-> Where species = 'Dog' or species = 'cat'
-> Group by species, sex;
+ --- + -- + ---- +
| Species | sex | count (*) |
+ --- + -- + ---- +
| Cat | f | 1 |
| Cat | M | 1 |
| Dog | f | 1 |
| Dog | M | 2 |
+ --- + -- + ---- +
Or, if you only need to know the number of sex-based animals with known gender:

Mysql> select species, sex, count (*) from pet
-> Where sex is not null
-> Group by species, sex;
+ --- + -- + ---- +
| Species | sex | count (*) |
+ --- + -- + ---- +
| Bird | f | 1 |
| Cat | f | 1 |
| Cat | M | 1 |
| Dog | f | 1 |
| Dog | M | 2 |
| Hamster | f | 1 |
| Snake | M | 1 |
+ --- + -- + ---- +
3.3.4.9. use more than one table
The pet table tracks which pet you have. If you want to record other related information, such as seeing a veterinarian in their life or when a descendant is born, you need another table. What should this table look like? Required:
· It needs to contain the pet name so that you know which animal each event belongs.

· You need a date to know when the event occurred.

· A field describing the event is required.

· If you want to classify events, you need an event type field.

Based on the above factors, the create table statement of the event table should be:

Mysql> Create Table Event (name varchar (20), date,
-> Type varchar (15), remark varchar (255 ));
For a pet table, the easiest way is to create a text file that contains information separated by delimiters to load the initial records:

Name
Date
Type
Remark

Fluffy
1995-05-15
Litter
4 kittens, 3 female, 1 male

Buffy
1993-06-23
Litter
5 puppies, 2 female, 3 male

Buffy
1994-06-19
Litter
3 puppies, 3 female

Chirpy
2017-03-21
Vet
Needed beak straightened

Slim
1997-08-03
Vet
Broken rib

Bowser
1991-10-12
Kennel
Fang
1991-10-12
Kennel
Fang
1998-08-28
Birthday
Gave him a new chew toy

Claws
1998-03-17
Birthday
Gave him a new flea collar

Whistler
1998-12-09
Birthday
First birthday
Use the following method to load records:

Mysql> load data local infile 'event.txt 'into table event;
According to what you learned from queries that have been run on the pet table, you should be able to search records in the event table. The principle is the same. But when cannot the event table answer any questions you may ask?

When they have a nest of small animals, suppose you want to find out the age of each pet. We have seen how to calculate the age by two dates. The event table contains the mother's production date, but to calculate the mother's age, you need her birth date, which is stored in the pet table. Two tables are required for query:

Mysql> select pet. Name,
-> (Year (date)-year (birth)-(right (date, 5) <right (birth, 5) as age,
-> Remark
-> From pet, event
-> Where pet. Name = event. Name and event. type = 'litter ';
+ --- + -- + ---------- +
| Name | age | remark |
+ --- + -- + ---------- +
| Fluffy | 2 | 4 kittens, 3 female, 1 male |
| Buffy | 4 | 5 puppies, 2 female, 3 male |
| Buffy | 5 | 3 puppies, 3 female |
+ --- + -- + ---------- +
Note the following:

The from clause lists two tables, because the Query Needs to extract information from two tables.
When combining information from multiple tables, you need to specify how the records in a table can match the records in other tables. This is simple because they all have a name column. The query uses the WHERE clause to match records in two tables based on the name value.
Because name is listed in two tables, you must specify which table to reference when referencing columns. You can add the table name to the column name.
You do not have to have two different tables for join. If you want to compare the records of a table with other records of the same table, you can join a table to itself. For example, in order to breed a spouse among your pets, you can use pet to associate yourself with a similar type of female:
Mysql> select p1.name, p1.sex, p2.name, p2.sex, p1.species
-> From PET as P1, pet as p2
-> Where p1.species = p2.species and p1.sex = 'F' and p2.sex = 'M ';
+ --- + -- + --- +
| Name | sex | species |
+ --- + -- + --- +
| Fluffy | f | claws | M | cat |
| Buffy | f | Fang | M | dog |
| Buffy | f | Bowser | M | dog |
+ --- + -- + --- +
In this query, we specify an alias for the table name so that the column can be referenced and the table instance associated with each column reference is more intuitive.

3.4. Obtain information about databases and tables. What if you forget the database or table name or the given table structure (for example, what is its column name? MySQL solves this problem by providing several statements about the database and its supported tables.
You have seen show databases, which lists the databases managed by the server. To find the Database Selected, use the database () function:

Mysql> select database ();
+ ---- +
| Database () |
+ ---- +
| Menagerie |
+ ---- +
If you have not selected any database, the result is null.

To find out what table the current database contains (for example, when you cannot determine the name of a table), run the following command:

Mysql> show tables;
+ ------- +
| Tables in menagerie |
+ ------- +
| Event |
| Pet |
+ ------- +
If you want to know the structure of a table, you can use the describe command; it displays the information of each column in the table:

Mysql> describe PET;
+ --- + ----- + -- + --- +
| FIELD | type | null | key | default | extra |
+ --- + ----- + -- + --- +
| Name | varchar (20) | Yes | null |
| Owner | varchar (20) | Yes | null |
| Species | varchar (20) | Yes | null |
| Sex | char (1) | Yes | null |
| Birth | date | Yes | null |
| Death | date | Yes | null |
+ --- + ----- + -- + --- +
Field indicates the column name. type indicates the column data type. null indicates whether the column can contain null values. Key indicates whether the column is indexed and default indicates the default value of the column.

If the table has an index, show index from tbl_name generates information about the index.
I found that I used
Select name from contact where name like
When '% A %', the results include the name of a and the name of the Chinese "new" also appears in the search results, this makes me want to figure out what the matching modes and rules of MySQL are like,
So I decided to check the information for details. In addition, regular expressions are also very common during matching! So I am going to record what I learned here!
The cause of this problem is: MySQL is case insensitive when querying strings, in programming MySQL, The ISO-8859 character set is generally used as the default character set, therefore, the case-sensitivity conversion of Chinese encoding Characters During the comparison process causes this phenomenon.
Solution
1. when creating a table, add the "binary" attribute to the fields that contain Chinese characters to make binary comparison. For example, change "name char (10)" to "name char (10) binary ". However, it is case-sensitive when you match this field in the table.
2. If you use the source code to compile MySQL, you can use the-with-charset = GBK parameter during compilation, so that MySQL directly supports Chinese searching and sorting.
3. Use the locate function of MySQL to determine. For example:
Select * from table where locate (substr, STR)> 0;
Locate () has two forms: locate (substr, STR), locate (substr, STR, POS ). Returns the position of substr in Str. If STR does not contain substr, return 0. This function is case insensitive.
4. use the SQL statement: Select * from table where fields like binary '% find % ', however, this is case-sensitive like 1. If you want to perform a case-insensitive query, use upper or lower for conversion.
5. Use binary and ucase functions and Concat functions. Ucase converts all English-speaking letters into uppercase letters, and Concat concatenates strings. The new SQL statement is as follows:
Select ID, title, name from achech_com.news where binary ucase (title) Like Concat ('%', ucase ('A'), '% ')
It can also be written as select ID, title, name from achech_com.news where binary ucase (title) Like ucase ('% A % ')
The search results are satisfactory, but the speed may be slow for N milliseconds. Because matching with like and % will affect the efficiency.

Regular Expression:
Regular Expressions are a powerful way to specify patterns for complex searches.

^
Start of the string following the matched string
Mysql> select "fonfo" Regexp "^ fo $";-> 0 (mismatch)
Mysql> select "Fofo" Regexp "^ FO";-> 1 (matching)

$
The end of the matched string
Mysql> select "Fono" Regexp "^ Fono $";-> 1 (matching)
Mysql> select "Fono" Regexp "^ fo $";-> 0 (mismatch)

.
Match any characters (including new lines)
Mysql> select "Fofo" Regexp "^ F. *";-> 1 (matching)
Mysql> select "fonfo" Regexp "^ F. *";-> 1 (matching)

A *
Match any number of A (including empty strings)
Mysql> select "ban" Regexp "^ ba * n";-> 1 (matching)
Mysql> select "baaan" Regexp "^ ba * n";-> 1 (matching)
Mysql> select "bn" Regexp "^ ba * n";-> 1 (indicating matching)

A +
Matches any sequence of one or more A characters.

Mysql> select "ban" Regexp "^ BA + N";-> 1 (matching)
Mysql> select "bn" Regexp "^ BA + N";-> 0 (indicating mismatch)

A?
Match one or zero
Mysql> select "bn" Regexp "^ Ba? N ";-> 1 (indicating matching)
Mysql> select "ban" Regexp "^ Ba? N ";-> 1 (indicating matching)
Mysql> select "Baan" Regexp "^ Ba? N ";-> 0 (indicating mismatch)

De&# 124; ABC
Match de or ABC
Mysql> select "pi" Regexp "PI & #124; APA";-> 1 (indicating matching)
Mysql> select "axe" Regexp "PI & #124; APA";-> 0 (indicating mismatch)
Mysql> select "APA" Regexp "PI & #124; APA";-> 1 (indicating matching)
Mysql> select "APA" Regexp "^ (PI & #124; APA) $";-> 1 (indicating matching)
Mysql> select "Pi" Regexp "^ (PI & #124; APA) $";-> 1 (indicating matching)
Mysql> select "pix" Regexp "^ (PI & #124; APA) $";-> 0 (indicating mismatch)

(ABC )*
Match any number of ABC (including empty strings)
Mysql> select "Pi" Regexp "^ (PI) * $";-> 1 (indicating matching)
Mysql> select "Pip" Regexp "^ (PI) * $";-> 0 (indicating mismatch)
Mysql> select "Pipi" Regexp "^ (PI) * $";-> 1 (indicating matching)

{1} {2, 3}
This is a more comprehensive method, which can implement the functions of the previous several Reserved Words
A *
Can be written as a {0 ,}
A
Can be written as a {1 ,}
A?
Can be written as a {0, 1}
There is only one integer parameter I in {}, indicating that the character can only appear I times; there is an integer parameter I in,
Followed by a ",", indicating that the character can appear I times or more than I times; there is only one integer parameter in,
Followed by a ",", followed by an integer parameter J, indicating that the character can only appear more than I times, less than J times
(Including I and j ). The integer parameter must be greater than or equal to 0 and less than or equal to re_dup_max (default value: 25 ).
5 ). If both m and n are given, m must be less than or equal to n.

[A-dx], [^ A-dx]
Match any character that is (or is not, if ^ is used) a, B, c, d, or X. The "-" character between two other characters constitutes a fan
It matches all characters starting from 1st characters to 2nd characters. For example, [0-9] matches any decimal number
. To include the text character "]", it must be followed by the brackets. To contain the text character "-", it must be written first or last. For any character that does not define any special meaning,
It only matches with itself.

Mysql> select "axbc" Regexp "[A-dxyz]";-> 1 (indicating matching)
Mysql> select "axbc" Regexp "^ [A-dxyz] $";-> 0 (indicating mismatch)
Mysql> select "axbc" Regexp "^ [A-dxyz] $";-> 1 (indicating matching)
Mysql> select "axbc" Regexp "^ [^ A-dxyz] $";-> 0 (indicating mismatch)
Mysql> select "gheis" Regexp "^ [^ A-dxyz] $";-> 1 (indicating matching)
Mysql> select "gheisa" Regexp "^ [^ A-dxyz] $";-> 0 (indicating no matching)

[[. Characters.]
Indicates the order of comparison elements. The Character Sequence in parentheses is unique. However, parentheses can contain wildcards,
So he can match more characters. For example, the regular expression [[. Ch.] * C matches the first five characters of chchcc.
.

[= Character_class =]
It indicates an equal class, which can replace other equal elements in the class, including its own. For example, if O and () are
For members of an equal class, [[= O =], [[= () =], and [O ()] are completely equivalent.

[: Character_class:]
In parentheses, the name of the character class is in the middle of [: And:], which can represent all characters of the class.
The character classes are named alnum, digit, punct, Alpha, graph, space, blank, lower, and uppe.
R, cntrl, print, and xdigit
Mysql> select "justalnums" Regexp "[[: alnum:]";-> 1 (indicating matching)
Mysql> select "!" Regexp "[[: alnum:]";-> 0 (not matching)

Alnum text and numeric characters
Alpha character
Blank white space characters
Cntrl control characters
Digit numeric characters
Graph character
Lower lowercase characters
Print graphics or space characters
Punct punctuation
Space, tab, new line, and carriage return
Upper uppercase characters
Xdigit hexadecimal numeric characters

[[: <:]
[[:>:]
Matches an empty string at the beginning and end of a word. the start and end of the word are not included in alnum.
Cannot contain underscores.
Mysql> select "a word a" Regexp "[[: <:] Word [[: >:]]";-> 1 (indicating matching)
Mysql> select "A xword a" Regexp "[[: <:] Word [[:]";-> 0 (indicating that the request does not match)
Mysql> select "weeknights" Regexp "^ (WEE & #124; week) (knights & #124; nights) $";-> 1 (indicating
Matching)

To use a text instance with special characters in a regular expression, add two backslash (\) characters before it. The MySQL parser is responsible for interpreting one of them, and the regular expression library is responsible for interpreting the other. For example, to match the string "1 + 2" that contains the special character "+", in the following regular expression, only the last one is correct:

Mysql> select '1 + 2' Regexp '1 + 2';-> 0

Mysql> select '1 + 2' Regexp '1 \ + 2';-> 0

Mysql> select '1 + 2' Regexp '1 \ + 2';-> 1

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.