当前位置:网站首页>SQL language

SQL language

2022-06-10 15:43:00 CaraYQ

SQL classification

SQL The function of language is mainly divided into the following 3 Categories: :

  1. DDL(Data Definition Languages, Data definition language ), These statements define different databases 、 surface 、 View 、 Index and other database objects , It can also be used to create 、 Delete 、 Modify the structure of database and data table . The main statement keywords include CREATEDROPALTER etc. .
  2. DML(Data Manipulation Language, Data operation language ), Used to add 、 Delete 、 Update and query database records , And check data integrity . The main statement keywords include INSERTDELETEUPDATESELECT etc. .

SELECT yes SQL The basis of language , Above all .

  1. DCL(Data Control Language, Data control language ), Used to define the database 、 surface 、 Field 、 User's access rights and security level . The main statement keywords include GRANTREVOKECOMMITROLLBACKSAVEPOINT etc. .

Because query statements are used very frequently , So many people bring out the query statement list :DQL( Data query language ). And alone will COMMITROLLBACK Take it out and call it TCL(Transaction Control Language, Transaction control language ).

SQL Rules and norms of language

The basic rule

One 、SQL It can be written on one or more lines . To improve readability , Write each clause separately , Use indent if necessary
Two 、 Every order is made with ; or \g or \G end ,

Only in cmd China and Israel \g or \G end , stay sqlyog China will report an error

3、 ... and 、 Keywords cannot be abbreviated or separated ,SQLyog Keywords will be marked in blue in .
Four 、 About punctuation

  1. All must be guaranteed () Single quotation marks Double quotes It ends in pairs
  2. Half angle input mode in English must be used
  3. String and date time data Use single quotes (' ') Express
  4. Alias of column Use double quotes (" "), And it is not recommended to omit as

SQL Case specification ( It is recommended that )

One 、MySQL stay Windows The environment is case insensitive , stay Linux The environment is case sensitive . because Windows It's not case sensitive by itself ,Linux distinguish

  1. Database name 、 Table name 、 The table alias 、 Variable names are strictly case sensitive
  2. keyword 、 Function name 、 Name ( Or field name )、 Alias of column ( The alias of the field ) It's case insensitive .

Two 、 A unified writing standard is recommended :

  1. Database name 、 Table name 、 Table alias 、 Field name 、 Fields, aliases, etc. are all lowercase
  2. SQL keyword 、 Function name 、 Bound variables, etc., are all capitalized

notes

 Single-line comments :# Note text (MySQL In a particular way )
 Single-line comments :--  Note text (-- Must be followed by a space .)
 Multiline comment :/*  Note text  */

Naming rules ( For the time being )

One 、 database 、 The table name must not exceed 30 Characters , Variable names are limited to 29 individual
Two 、 Must contain only A–Z, a–z, 0–9, _ common 63 Characters
3、 ... and 、 Database name 、 Table name 、 Do not include spaces in object names such as field names
Four 、 The same MySQL In software , The database cannot have the same name ; In the same library , A watch cannot have the same name ; In the same table , The field cannot have the same name
5、 ... and 、 You must ensure that your field has no and reserved words 、 Database systems or common methods conflict . If you insist on using , Please be there. SQL Use in statement `( mark of emphasis ) Lead up
6、 ... and 、 Keep field names and types consistent , When naming fields and specifying data types for them, be sure to ensure consistency . If the data type is an integer in a table , Then don't turn into character in another table

# The following two sentences are the same , Case insensitive 
show databases;
SHOW DATABASES;
# Create a table 
#create table student info(...); # Table name error , Because the table name has spaces 
create table student_info(...);
# among order Use `` Floating horn , because order It has the same name as the predefined identifier such as system keyword or system function name 
CREATE TABLE `order`(
	id INT,
	lname VARCHAR(20)
);
select id as " Number ", `name` as " full name " from t_stu; # When it comes to aliases ,as All can be omitted 
select id as  Number , `name` as  full name  from t_stu; # If there is no space in the field alias , Then you can omit ""
select id as  Ed   Number , `name` as  surname   name  from t_stu; # error , If there are spaces in the field alias , Then you can't omit ""

Data import instruction

Method :

  1. Log in to the command line client mysql, Use source Command import , Format :source File full pathname , Such as :mysql> source d:\mysqldb.sql
  2. Tools based on specific graphical interfaces can import data : Tools —— perform SQL Script —— Select file to execute

Basic SELECT sentence

SELECT…

SELECT 1; # There are no clauses 
SELECT 9/2; # There are no clauses 
SELECT 1 + 1,3 * 2; # There are no clauses 

The last line is equivalent to :

SELECT 1 + 1,3 * 2
FROM DUAL; #dual: False watch 

SELECT Field 1, Field 2,… FROM Table name

One 、 grammar :

SELECT  Identify which fields or columns to select 
FROM  Identifies which table to choose from 

Two 、 Select all fields or columns :

SELECT *
FROM departments;

3、 ... and 、 Select a specific column :

SELECT department_id, location_id
FROM departments;

Four 、 In general , Unless you need to use all the field data in the table , It is best not to use wildcards *. Using wildcards can save time in entering query statements , However, getting unwanted column data often reduces the efficiency of queries and applications used . The advantage of wildcards is , When you don't know the name of the desired column , You can get them through it . In production environment , It is not recommended that you use SELECT * The query .

Alias of column

One 、 Rename a column
Two 、 How to write it :

  1. Keep up with the column name , Add keywords between column names and aliases AS,AS It can be omitted
  2. Aliases use double quotes , To include spaces or special characters in the alias and be case sensitive .
#  Keep up with the column name , Add keywords between column names and aliases AS,AS It can be omitted 
SELECT last_name AS name, commission_pct comm 
FROM employees;
#  Aliases use double quotes 
SELECT last_name "Name", salary*12 "Annual Salary"
FROM employees;

Remove duplicate lines

One 、 By default , The query will return all rows , Include repeating lines . But we can SELECT Use keywords in statements DISTINCT Remove duplicate lines

SELECT DISTINCT department_id
FROM employees;

Two 、 in the light of

SELECT DISTINCT department_id,salary
FROM employees;

Be careful :

  1. DISTINCT Need to precede all column names , If it is written below, it will report an error
SELECT salary, DISTINCT department_id, 
FROM employees;
  1. DISTINCT In fact, it is to de duplicate the combination of all the following column names , The query results are as follows :
     Insert picture description here

Null values participate in the operation

One 、 Null value :null
Two 、 All operators or column values encountered null value , The result of the operation is null

SELECT employee_id,salary,commission_pct, 12 * salary * (1 + commission_pct) "annual_sal"
FROM employees;

Be careful : A null value is not equal to an empty string . The length of an empty string is 0, The length of a null value is null . and , stay MySQL Inside , Null values take up space .

mark of emphasis

When the table name / When the field name and keyword name are the same , Will report a mistake :

mysql> SELECT * FROM ORDER;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'ORDER' at line 1

Solution : Use a bullet to put the table name / The field name is wrapped :

mysql> SELECT * FROM `ORDER`;

We need to ensure that the fields in the table 、 Table names, etc. have no and reserved words 、 Database systems or common methods conflict . If it's really the same , Please be there. SQL A double sign is used in the statement .

Query constant

One 、SELECT The query can also query constants , Is in the SELECT Add a fixed constant column to the query result . The value of this column is specified by us , Not dynamically extracted from the data table .
Two 、 You might ask why we have to query constants ?
SQL Medium SELECT Grammar does provide this function , Generally speaking, we only query data from one table , There is usually no need to add a fixed constant column , But if we want to integrate different data sources , Use the constant sequence as the marker of this table , You need to query constants . for instance , We want to be right employees Query the employee name in the data table , At the same time, add a column of fields corporation, The fixed value of this field is “ Silicon Valley ”, It can be written like this :SELECT ' Silicon Valley ' as corporation, last_name FROM employees;

Displays the details of the fields in the table

Use DESCRIBE or DESC command , Displays the details of the fields in the table , Such as :

DESCRIBE employees;
 or 
DESC employees;

 Insert picture description here
The meanings of each field are explained as follows :

  1. Field: Field name .
  2. Type: Represents the field type , here barcode、goodsname It's textual ,price It's of type integer .
  3. Null: Indicates whether the column can store NULL value .
  4. Key: Indicates whether the column is indexed .PRI Indicates that the column is part of the table primary key ;UNI Indicates that the column is UNIQUE Part of index ;MUL Indicates that a given value is allowed to appear more than once in a column .
  5. Default: Indicates whether the column has a default value , If there is , So what's the value .
  6. Extra: Represents additional information about a given column that can be obtained , for example AUTO_INCREMENT etc. .

Filtering data

One 、 Just want to query data that meets certain conditions :

SELECT  Field 1, Field 2
FROM  Table name 
WHERE  Filter conditions 

Be careful :

  1. Use WHERE Clause , Filter out rows that do not meet the criteria
  2. WHERE Clause in the wake of FROM Clause

Two 、 practice :

# practice : Inquire about 90 Employee information of department No 
SELECT * 
FROM employees
# Filter conditions , The statement in FROM Behind the structure 
WHERE department_id = 90;

# practice : Inquire about last_name by 'King' Employee information 
SELECT * 
FROM EMPLOYEES
WHERE LAST_NAME = 'King'; 

Operator

Arithmetic operator

One 、 Arithmetic operator :+-*/div%mod
Two 、
 Insert picture description here

Addition and subtraction operators

SELECT 100, 100 + 0, 100 - 0, 100 + 50, 100 + 50 - 30, 100 + 35.5, 100 - 35.5 
FROM DUAL;

#  stay SQL in ,+ No connection , It means addition . here , Will convert the string to a numeric value ( Implicit conversion )
SELECT 100 + '1'  #  stay Java In language , The result is :1001, The result here is 101
FROM DUAL;

SELECT 100 + 'a' # At this time will be 'a' regard as 0 Handle 
FROM DUAL;

SELECT 100 + NULL  # null Value participates in the operation , The result is null
FROM DUAL;

 Insert picture description here

Conclusion :

  1. An integer type value adds and subtracts integers , The result is still an integer ;
  2. An integer type value adds and subtracts floating-point numbers , The result is a floating point number ;
  3. Addition and subtraction have the same priority , The result of adding before subtracting is the same as that of subtracting before adding ;
  4. stay Java in ,+ If there is a string on the left and right sides of , Then it represents the splicing of strings . But in MySQL5. in + It only means that the values are added . If a non numeric type is encountered , First try to convert to a value , If the transfer fails , Just press the 0 Calculation .( Add :MySQL String functions are used in string splicing CONCAT() Realization )

Multiplication and division operators

SELECT 100, 100 * 1, 100 * 1.0, 100 / 2, 100 + 2 * 5 / 2, 100 / 3, 100 DIV 0
FROM dual;

 Insert picture description here

Division is not always possible ,SQL The direct default division is endless , So all the division results are preserved 4 Decimal place

Conclusion :

  1. A number times an integer 1 And divided by an integer 1 After that, you still get the original number ;
  2. A number times a floating point number 1 And divided by floating point numbers 1 Then it becomes a floating point number , The value is equal to the original number ;
  3. A number divided by an integer , Whether or not we can eliminate , The result is a floating point number ;
  4. Divide one number by another , When there is no end to it , The result is a floating point number , And keep it after the decimal point 4 position ;
  5. Multiplication and division have the same priority , Perform the multiply then divide operation and the divide before multiply operation , The results are the same .
  6. In mathematics ,0 Cannot be used as a divisor , stay MySQL in , A number divided by 0 by NULL.

Modulus operation % mod

SELECT 12 % 3,12 % 5, 12 MOD -5,-12 % 5,-12 % -5
FROM DUAL;

 Insert picture description here

The sign and the first number of the result ( By modulus ) Agreement

Comparison operator

One 、 The comparison operator is used to compare the operands on the left and right of the expression , If the comparison result is true, it returns 1, If the comparison result is false, it returns 0, Other cases return to NULL.
Two 、 Comparison operators are often used as SELECT Use the conditions of the query statement , Return qualified result records .
 Insert picture description here
 Insert picture description here

The equal sign operator

One 、 The equal sign operator (=) Judge the values on both sides of the equal sign 、 Whether the string or expression is equal , If equal, return 1, Return if not equal 0.
Two 、 Follow these rules :

  1. If the values on both sides of the equal sign 、 String or expression All are strings , Compare the characters in each string ASCII Whether the codes are equal .
  2. If the values on both sides of the equal sign Are integers. , Then compare the size of the two values according to integers .
  3. If the value on both sides of the equal sign is an integer , The other is the string , be MySQL Will convert strings to numbers for comparison .
  4. If the values on both sides of the equal sign 、 One of the strings or expressions is NULL, The comparison result is NULL.

SQL The assignment symbol in... Is used :=

SELECT 1 = 2,1 != 2,1 = '1',1 = 'a',0 = 'a' # The string has an implicit conversion . If the conversion of values is unsuccessful , As 0
FROM DUAL;

SELECT 'a' = 'a','ab' = 'ab','a' = 'b' # If there are strings on both sides , According to ANSI Compare with the rules of comparison .
FROM DUAL;

SELECT 1 = NULL,NULL = NULL #  As long as there is null Participate in judgment , The results for null
FROM DUAL;

SELECT last_name,salary,commission_pct
FROM employees
#where salary = 6000;
WHERE commission_pct = NULL;  # Execute at this time , There will be no result 

Security equals operator

Security equals operator (<=>) And equals operator (=) It's similar , The only difference is <=> It can be used for NULL Judge . In both operands are NULL when , Its return value is 1, Not for NULL; When an operand is NULL when , Its return value is 0, Not for NULL

SELECT 1 <=> 2,1 <=> '1',1 <=> 'a',0 <=> 'a'
FROM DUAL;

SELECT 1 <=> NULL, NULL <=> NULL
FROM DUAL;

# practice : In the query table commission_pct by null What's the data of 
SELECT last_name,salary,commission_pct
FROM employees
WHERE commission_pct <=> NULL;

Not equal to the operator

Not equal to the operator (<> and !=) Used to judge the numbers on both sides 、 Whether the values of strings or expressions are not equal , Returns if not equal 1, Equal returns 0. Not equal to operator cannot judge NULL value . If either of the values on both sides is NULL, Or on both sides NULL, The result is NULL.

SELECT 3 <> 2,'4' <> NULL, '' != NULL,NULL != NULL
FROM DUAL;

Air transport operator and air transport operator

One 、 Air transport operator (IS NULL perhaps ISNULL) Determines whether a value is NULL, If NULL Then return to 1, Otherwise return to 0
Two 、 Non air transport operators (IS NOT NULL) Judge whether a value is not NULL, If not for NULL Then return to 1, Otherwise return to 0.

# practice : In the query table commission_pct by null What's the data of 
SELECT last_name,salary,commission_pct
FROM employees
WHERE commission_pct IS NULL;
# or 
SELECT last_name,salary,commission_pct
FROM employees
WHERE ISNULL(commission_pct);

# practice : In the query table commission_pct Not for null What's the data of 
SELECT last_name,salary,commission_pct
FROM employees
WHERE commission_pct IS NOT NULL;
# or 
SELECT last_name,salary,commission_pct
FROM employees
WHERE NOT commission_pct <=> NULL;

Maximum operator 、 Minimum operator

One 、 Minimum operator :LEAST( value 1, value 2,..., value n). among ,“ value n” Indicates that there is... In the parameter list n It's worth . In the case of two or more parameters , Return minimum .
Two 、 Maximum operator :GREATEST( value 1, value 2,..., value n). among ,n Indicates that there is... In the parameter list n It's worth . When there are two or more parameters , The return value is the maximum value .
3、 ... and 、 When the parameter is an integer or floating point number ,GREATEST Will return the largest value ; When the parameter is a string , Returns the last character in the alphabet ; When there is... In the comparison value list NULL when , Cannot judge size , The return value is NULL.

SELECT LEAST('g','b','t','m'),GREATEST('g','b','t','m')
FROM DUAL;

SELECT LEAST(first_name,last_name),LEAST(LENGTH(first_name),LENGTH(last_name))
FROM employees;

BETWEEN AND Operator

One 、 grammar :BETWEEN Conditional lower bound 1 AND Conditional upper bound 2, Query criteria 1 And conditions 2 Data in scope , Including boundaries
Two 、 Finding a range

# Check salary at 6000  To  8000 Employee information 
SELECT employee_id,last_name,salary
FROM employees
#where salary between 6000 and 8000;
WHERE salary >= 6000 && salary <= 8000;

# In exchange for 6000  and  8000 after , No data to query 
SELECT employee_id,last_name,salary
FROM employees
WHERE salary BETWEEN 8000 AND 6000;

# The salary inquiry is not available 6000  To  8000 Employee information 
SELECT employee_id,last_name,salary
FROM employees
WHERE salary NOT BETWEEN 6000 AND 8000;
#where salary < 6000 or salary > 8000;

IN Operator 、NOT IN Operator

One 、IN Operator Syntax :in ( aggregate ), Used to determine whether a given value is IN A value in the list , If so, return 1, Otherwise return to 0. If the given value is NULL, perhaps IN List exists NULL, The result is NULL.
Two 、NOT IN Operator :not in ( aggregate ), Used to determine whether a given value is not IN A value in the list , If not IN A value in the list , Then return to 1, Otherwise return to 0.
3、 ... and 、 Search for discrete values

# practice : The inquiry department is 10,20,30 Employee information of the Department 
SELECT last_name,salary,department_id
FROM employees
#where department_id = 10 or department_id = 20 or department_id = 30;
WHERE department_id IN (10,20,30);

# practice : Query salary is not 6000,7000,8000 Employee information 
SELECT last_name,salary,department_id
FROM employees
WHERE salary NOT IN (6000,7000,8000);

LIKE Operator

One 、 Mainly used to match strings , Usually used for fuzzy matching , If the condition is met, return 1, Otherwise return to
0. If the given value or matching condition is NULL, Then the returned result is NULL.
Two 、 Common wildcards :

  1. % : A character representing an indefinite number (1 One or more )
  2. _ : Represents an uncertain character , Equivalent to placeholder
# practice : Inquire about last_name Contains characters 'a' Employee information 
SELECT last_name
FROM employees
WHERE last_name LIKE '%a%';

# practice : Inquire about last_name With the character 'a' Employee information at the beginning 
SELECT last_name
FROM employees
WHERE last_name LIKE 'a%';

# practice : Inquire about last_name Contains characters 'a' And contains characters 'e' Employee information 
# How to write it 1:
SELECT last_name
FROM employees
WHERE last_name LIKE '%a%' AND last_name LIKE '%e%';
# How to write it 2:
SELECT last_name
FROM employees
WHERE last_name LIKE '%a%e%' OR last_name LIKE '%e%a%';

# _ : Represents an uncertain character 
# practice : Query the first 3 The characters are 'a' Employee information 
SELECT last_name
FROM employees
WHERE last_name LIKE '__a%';

# practice : Query the first 2 The characters are _ And the first 3 The characters are 'a' Employee information 
# You need to use escape characters : \ 
SELECT last_name
FROM employees
WHERE last_name LIKE '_\_a%';

# perhaps  ( understand )  The default transition character is \, But you can use ESCAPE Specify the transfer character , as follows :
SELECT last_name
FROM employees
WHERE last_name LIKE '_$_a%' ESCAPE '$';

REGEXP Operator

One 、REGEXP Operators are used to match strings , The grammar format is : expr REGEXP Matching condition . If expr Meet the matching conditions , return 1; If not satisfied , return 0. if expr Or any one of the matching conditions is NULL, The result is NULL.
Two 、REGEXP Operator when matching , The following wildcards are commonly used :

  1. ^ Matches a string that begins with the character after the character .
  2. $ Matches a string that ends with a character that precedes the character .
  3. . Match any single character .
  4. [...] Match any character in square brackets . for example ,[abc] matching a or b or c. To name the range of characters , Use one -.[a-z] Match any letter , and [0-9] Match any number .
  5. * Match zero or more characters before it . for example ,x* Match any number of x character ,[0-9]* Match any number of numbers , and * Match any number of any characters .

Logical operators

 Insert picture description here
One 、 Logic is not (NOT or !) Operator means when the given value is 0 When to return to 1; When the given value is non 0 Value returns 0; When the given value is NULL when , return NULL.
Two 、 Logic and (AND or &&) Operator is when all values given are non 0 value , And not for NULL when , return 1; When a given value or values are 0 When you return to 0; Otherwise return to NULL.
3、 ... and 、 Logic or (OR or ||) The operator is when the given value is not NULL, And any value is non 0 When the value of , Then return to 1, Otherwise return to 0; When a value is NULL, And the other value is non 0 When the value of , return 1, Otherwise return to NULL; When both values are NULL when , return NULL.

OR You can talk to AND Use it together , But pay attention to the priority of the two when using , because AND Has a higher priority than OR, So first of all AND The operands on both sides operate , And again OR The operands in .

Four 、 Logical XOR (XOR) Operator is when any one of the given values is NULL when , Then return to NULL; If two are not NULL The values are all 0 Or it doesn't mean 0 when , Then return to 0; If a value is 0, The other value is not 0 when , Then return to 1.

# or and 
SELECT last_name,salary,department_id
FROM employees
#where department_id = 10 or department_id = 20;
#where department_id = 10 and department_id = 20;
WHERE department_id = 50 AND salary > 6000;

# not 
SELECT last_name,salary,department_id
FROM employees
#where salary not between 6000 and 8000;
#where commission_pct is not null;
WHERE NOT commission_pct <=> NULL;

# XOR : Pursuing " different "
SELECT last_name,salary,department_id
FROM employees
WHERE department_id = 50 XOR salary > 6000;

An operator

 Insert picture description here
One 、 Bitwise AND (&) Operator : When the value of the binary bit corresponding to the given value is 1 when , Then the bit returns 1, Otherwise return to 0.
Two 、 Press bit or (|) Operator : When one or two of the binary values corresponding to a given value are 1 when , Then the bit returns 1, Otherwise return to 0.
3、 ... and 、 Bitwise XOR (^) Operator : When the value of the binary bit corresponding to the given value is different , This bit returns 1, Same returns 0
Four 、 According to the not (~) Operator : take 1 Turn into 0, take 0 Turn into 1.
5、 ... and 、 Right shift to position (>>) Operator shifts all bits of the binary number of a given value to the right by the specified number of bits . Shift the specified number of bits to the right , The lower value on the right is removed and discarded , The left high position is empty with 0 A filling .
6、 ... and 、 Move left according to position (<<) Operator shifts all bits of the binary number of a given value to the left by the specified number of bits . Move the specified number of bits left , The higher left value is removed and discarded , On the right side, the low position is left by 0 A filling .

SELECT 12 & 5, 12 | 5,12 ^ 5 
FROM DUAL;

SELECT 10 & ~1 FROM DUAL;

# Meet... Within a certain range : Every move to the left 1 position , Equivalent to times 2; Every move to the right , Equivalent to divided by 2.
SELECT 4 << 1 , 8 >> 1
FROM DUAL;

Operator priority

 Insert picture description here
The larger the number , The higher the priority , Operators with higher priority are calculated first . You can see , The assignment operator has the lowest priority , Use () Enclosed expressions have the highest priority

Using regular expression queries

One 、REGEXP A list of common character matches in the operator :
 Insert picture description here
Two 、 Query records starting with a specific character or string . character ^ Matches text that begins with a specific character or string . stay fruits In the table , Inquire about f_name Fields are represented by letters ‘b’ The first record :SELECT * FROM fruits WHERE f_name REGEXP '^b';
3、 ... and 、 Query records ending with a specific character or string . character $ Matches text that ends with a specific character or string . stay fruits In the table , Inquire about f_name Fields are represented by letters ‘y’ The record at the end :SELECT * FROM fruits WHERE f_name REGEXP 'b$';
Four 、 Use symbols . To replace any character in the string . stay fruits In the table , Inquire about f_name field value
Contain letters ‘a’ And ‘g’ And there is only one letter between two letters :SELECT * FROM fruits WHERE f_name REGEXP 'a.g';
5、 ... and 、 asterisk * Match the preceding character any number of times , Include 0 Time . plus + Match the preceding character at least once . stay fruits In the table , Inquire about f_name Field values are in letters ‘b’ And ‘b’ The letters appear after them ‘a’ At least one record :SELECT * FROM fruits WHERE f_name REGEXP '^ba+';
6、 ... and 、 A regular expression can match a specified string , As long as this string is in the query text , To match multiple strings , Use separator between multiple strings | separate .

  1. stay fruits In the table , Inquire about f_name The field value contains a string “on” The record of :SELECT * FROM fruits WHERE f_name REGEXP 'on';
  2. stay fruits In the table , Inquire about f_name The field value contains a string “on” perhaps “ap” The record of :SELECT * FROM fruits WHERE f_name REGEXP 'on|ap';

LIKE Operator can also match the specified string , but LIKE If the matching string appears in the middle of the text , You can't find it , The corresponding line will not return .REGEXP Match within text , If the matched string appears in the text ,REGEXP It will be found , The corresponding line will also be returned .
stay fruits In the table , Use LIKE Operator query f_name The field values for “on” The record of :SELECT * FROM fruits WHERE f_name like 'on';, result :Empty set(0.00 sec)

7、 ... and 、 Matches any one of the specified characters . square brackets [] Specify a character set , Match only any of these characters , This is the text you are looking for .

  1. stay fruits In the table , lookup f_name The field contains letters ‘o’ perhaps ‘t’ The record of :SELECT * FROM fruits WHERE f_name REGEXP '[ot]';
  2. stay fruits In the table , Inquire about s_id The field contains 4、5 perhaps 6 The record of :SELECT * FROM fruits WHERE s_id REGEXP '[456]';

8、 ... and 、 Matches characters other than the specified characters [^ Character set ] Matches any character that is not in the specified set . stay fruits In the table , Inquire about f_id The field contains letters a-e And number 1-2 Records of characters other than :SELECT * FROM fruits WHERE s_id REGEXP '[^a-e1-2]';
Nine 、 Use {n,} perhaps {n,m} To specify the number of consecutive occurrences of the string . character string {n,} Means at least match n The next preceding character ; character string {n,m} Indicates that the matching preceding string is not less than n Time , Not more than m Time . for example ,a{2,} For letters a Continuous occurrence of at least 2 Time , It can also be greater than 2 Time ;a{2,4} For letters a Continuous occurrence of the least 2 Time , Not more than 4 Time .

  1. stay fruits In the table , Inquire about f_name A letter appears in the field value ‘x’ At least 2 The second record :SELECT * FROM fruits WHERE f_name REGEXP 'x{2,}';
  2. stay fruits In the table , Inquire about f_name The field value appears as a string “ba” least 1 Time 、 most 3 The second record :SELECT * FROM fruits WHERE f_name REGEXP 'ba{1,3}';
原网站

版权声明
本文为[CaraYQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101526281605.html