Basic knowledge and examples of MySQL functions and MySQL data operations in mainstream databases

Article directory

content

Article directory

foreword

4.3, MySQL function

math function

String functions

date and time functions

Conditional Judgment Function

system information function

encryption function

other functions

4.4, MySQL data operation

data management

data addition

Insert single or multiple rows of records

Insert data using subqueries

Simple data query

Data Update

data deletion

Data deletion (TRUNCATE)


foreword

This article mainly talks about MySQL functions in the database and MySQL data operations. In fact, some operations have been written before. You can go to the column to find the corresponding articles. In addition, the friends who have passed by will like and follow and then go, welcome to communicate in the comment area, and let's work together to grow together!

refill


4.3 、MySQL function

MySQL functions are mainly divided into the following categories according to their functions:

math function

Mathematical functions are mainly used to process numbers, including integers, floating-point numbers, etc.

Mathematical functions include absolute value functions, sine functions, cosine functions, functions to obtain random numbers, etc. as follows:

abs: Returns the absolute value of the expression

acos: arc cosine function, returns the angle value in radians

asin: arcsine function, returns the angle value in radians

atan: arc tangent function, returns the angle value in radians

ceil: Returns the smallest integer greater than or equal to the specified numeric expression

cos: returns the cosine value

degree: converts radian values ​​to degrees

exp: Returns the value of e where the given expression is the exponent

floor: Returns the largest integer less than or equal to the specified numeric expression

greatest: get the largest value in a set of numbers

Least: Get the smallest value in a set of numbers

log: returns the natural logarithm of the given expression

log10: Returns the base 10 logarithm of the given expression

PI: constant, pi

pow: Returns the value of the given expression raised to the specified power

radians: converts angle values ​​to radians

rand: returns a random noat number between 0 and 1

round: Returns the value of the expression specifying the number of decimal places

sign: returns the sign of a number

sin: returns the sine value

sqrt: Returns the square root of the given expression

tan: returns the tangent value

example:

SELECT mod(31,8), floor(3.67), ceil(4.71), log(2.7);

Example: Use random number rand() and rounding round() to output any integer between 10~50 and 15~55. The random number returned by the random function rand() is greater than or equal to 0 and less than 1. round(x,y) returns the value of x to y decimal places, rounding off when truncation.

SELECT RAND(),ROUND(40*RAND(),0), 10+round(40*rand(),0),15+round(40*rand(),0);

String functions

Mainly used for working with string data and expressions. The string functions in MySQL include calculating the length of strings, combining functions, replacing functions, comparing functions, and finding string position functions. as follows:

char_length: Returns the number of characters in the string.

concat: returns the string generated by the connection parameters

left: returns the specified number of characters starting from the left side of the string

length: returns the length in bytes of the given string

lower: Returns a character expression after converting uppercase character data to lowercase character data

trim: Returns a character expression after removing starting and ending spaces

replace: Replace all occurrences of the 2nd given string expression in the first string expression with the 3rd expression

repeat: Repeat a character expression a specified number of times

reverse: returns the reverse of a character expression

right: returns the specified number of characters starting from the right side of the string

ltrim/rtrim: Return a string after removing leading/trailing spaces

space: returns a string consisting of repeated spaces

substring: seek substring function

upper: Returns a character expression that converts lowercase character data to uppercase

Example: Use the concat() function to concatenate strings, and the lower() function converts them to lowercase letters. The concat() function returns the string from the concatenation of the parameters, or null if either parameter is null. There can be more than 2 parameters. Numeric arguments are converted to the equivalent string form.

SELECT lower(concat("MY","SQL","8.0")),concat("ABC",null,"DEF"),

concat("ABC","DEF");

Example: Use the trim() function to remove spaces on both sides of a string. Then use the concat() function to connect them.

SELECT '(  qwe  )', concat('(',trim(' qwe '),')');

Example: Use the substring() function to return the specified string (the second to fourth digits as follows, if there is only one number, it means from that digit to the end), and then use reverse() to output in reverse order

SELECT substring('ABCDEF',2,4), reverse(substring('ABCDEF',2));

date and time functions

Mainly used for working with date and time data in tables. Date and time functions include functions to obtain the current date, functions to obtain the current time, functions to calculate dates, functions to calculate time, and so on.

curdate: Get the date of the current system

curtime: Get the current system time

date_add: can add date and time

date_sub: can perform subtraction operations on dates and times

datediff: Calculate the number of days between two dates

date_format: used to format date values

day: get the date integer of the specified date

dayname: Display in English name, return the day of the week for the specified date, such as Tuesday, etc.

dayofmonth: Returns the ordinal number of the specified date in a month

dayofweek: returns the ordinal number of the specified date in a week

dayofyear: Returns the ordinal number of the specified date in the year

hour: returns the hour of the specified time

minute: returns the minute of the specified time

month: Get the month integer of the specified date

now/sysdayte: returns the current date and time

quarter: Get the quarter integer of the specified date

second: returns the number of seconds in the specified time

time_format: used to format time values

Example: use curdate() to return the current date, curtime() to return the current time

SELECT curdate(),curtime();

Example: The specified date returned is the day of the year, the day of the month, and the day of the week (the first day of the week is Sunday).

SELECT dayofyear(20200130),dayofmonth('2022-09-18'),dayofweek(now());

The date_add() and date_sub() functions can be used to add and subtract date values ​​to dates and times, respectively.

格式:date_add | date_sub(date, interval int keyword);

Among them: date represents the date and time, and the interval keyword represents a time interval. The following are keywords

and the format of the corresponding interval value

day: date

minute: minute

day_hour: date:hour

minute_second:minute:second

day_minute:date:hour:minute

month: month

day_second:date:hour:minute:second

second: seconds

hour: hour

year: year

hour_minute: hour:minute

year_month: year-month

hour_second:hour:minute:second

Example: Calculate what time is 15 minutes before the specified time (subtract 15 minutes from the specified time). Calculate what time is 15 minutes after the specified time (add 15 minutes to the specified time)

SELECT date_sub('2020-09-30 10:10:10' , interval 15 minute),DATE_ADD('2020-09-30 10:10:10',INTERVAL 15 minute);

Example: How many days are left until September 18. Use datediff to calculate the number of days between two dates (hehe, there are 168 days left for birthdays)

SELECT datediff('2020-12-31',now());

The date_format() and time_format() functions can be used to format date and time values.

格式:date_format/ time_format(date | time, fmt)

date and time are date and time values ​​that need to be formatted; fmt is the formatted form of date and time values.

The format of keywords and interval values ​​is as follows:

%oa: Abbreviated week name (Sun, Mon...>

%p: AM or PM

%b: Abbreviated month name (Jan, Feb...)

%r: time, in 12-hour format

%d: the number of days in the month

%S: seconds(00, 01)

%H %h: hours, in 24-hour and 12-hour formats respectively

%T: time, in 24-hour format

%i: minutes (00, 01..>

%ow : day of the week (0, 1)

%j: Day of the year ((001, 002..)

%w: the name of the week in long form (Sunday, Monday...)

%m: month, 2 digits (00,01...)

%Y: year, 4 digits

Example: output date and output time according to the specified format code.

SELECT date_format(now(), '%W,%d,%m, %Y ,%T,%p'),

time_format('16:20:10' ,' %H %i %S');

Conditional Judgment Function

The conditional judgment function is also called the control flow function, which executes the corresponding flow according to different conditions met.

if(expr,v1,v2): If the expression expr is true (expr<>0 and expr<>NULL), return v1, otherwise return v2.

ifnull(v1,v2): If v1 is not NULL, return v1, otherwise return v2.

case expr when v1 then r1 ...[else rn] end

If the expr value is equal to a certain vn, the result after the corresponding then is returned, and if all values ​​are not equal, the rn after the else is returned.

Example: Use the if() function for conditional judgment

SELECT if(1>2,1,2),if(1>2,'yes' ,'no');

Example: Conditional judgment with the ifnull() function

SELECT ifnull(1,2),ifnull(null,10),ifnull(1/0,'error');

Example: Use case when statement to perform branch operation

SELECT case 2 when 1 then 'one' when 2 then 'two' else 'more' end;

system information function

The system information function is used to query the system information of the MySQL database.

The functions and corresponding functions are as follows:

Database(): Returns the current database name

benchmark(n, expr): run the expression expr repeatedly n times

charset(str): returns the character set of the string str

connection_id(): Returns the number of times the current client connects to the server

found_rows(): Returns the number of rows of records returned by the last MySQL>select query (not limited by the limit statement)

get_lock(str, dur): Get a lock named by the string str with a delay of dur seconds

is_free_lock(str): Check if the lock named by str is released

last_insert_id(): Returns the value of the last autoincrement id automatically generated by the system

master pos_wait(log, pos, dur): lock the master server for dur seconds until the slave server synchronizes with the position pos specified by the master server's log log

release_lock(str): release the lock named by the string str

user() or system_user(): returns the current login user name

version(): Returns the version of the MySQL server

Example: Return the MySQL server version, current database name and current user name information, and check the number of times the current user connects to the MySQL server.

SELECT version(), database(), user(), connection_id();

encryption function

The encryption function is mainly used to encrypt and interface data to ensure that some important data cannot be obtained, thereby ensuring the security of the database. The function is as follows:

MD5(str): Calculates an md5 12s bit checksum for the string. The value is returned as a binary string of 32 hexadecimal digits.

SHA(str): Calculate and return the encrypted password string from the original plaintext password str, and return NULL when the parameter is NULL. Safer than md5.

SHA(str, hash_length): Encrypt str using hash_length as the length. The supported values ​​for hash_length are 224, 256, 384, 512 and 0. where 0 is equivalent to 256

Example: Encrypt with password(str) function

SELECT md5('ice'), sha('ice'), sha2('ice',256);

other functions

Formatting function: FORMAT(x,n) Formats the value x, and rounds it to n digits after the decimal point, and returns the result in the form of a string. If n is 0, the returned result function does not contain a fractional part.

例:SELECT format(12345.123456,4), format(12345.1,4), format(12345.1,0);

Function to change character set: CONVERT(..USING...) is used to convert data between different character sets

Example: Convert a given string character set to utf8

SELECT charset('asd'),charset(convert('asd' using utf8));

4.4 , MySQL data operation

data management

The data in the table can be managed by using data manipulation language (DML operations include adding, updating, and deleting operations on table data) and data query language (DQL operations including query operations on table data).

data addition

Add data using INSERT INTO statement

Insert single or multiple rows of records

INSERT INTO table name [(column name 1, column name 2...)] VALUES (column name 1 data 1, column name 2 data 1...), (column name 1 data 2, column name 2 data data 2)..;

in:

If no column names are specified in the INTO clause, the number, order, and type of column values ​​in the VALUES clause must match the number, order, and type of columns in the table

If the column name is specified in the INTO clause, the number, order, and type of column values ​​provided in the VALUES clause must correspond to the number, order, and type of the specified column by position

[Example] Insert a row of records into the department table

INSERT INTO department(deptno,dname,loc)VALUES(50,'name50','loc50');

Example: Insert multiple records into employee table

INSERT INTO employee VALUES

(1001,'zs ','PROGRAMMER',1002,'2015-10-20',1000,null,50),

(1002,'ls','MANAGER',null,'2010-01-01',3000,500,50),

(1003, 'ww', 'PROGRAMMER', 1002, '2012-12-30', 2000,200,50);

Example: Insert data into the specified field of the employee table

INSERT INTO employee(empno,ename,job,hiredate,sal,deptno)

VALUES(1004,'test ,'CLERK' ,2016-10-20',2000,50);

Insert data using subqueries

INSERT INTO tablename1 SELECT *|[columnname1...] FROM tablename2;

Inserting data from other tables into a table is also a way of inserting data in batches. But note that the same structure is required.

Example: Insert the records of the DEPT table into the DEPARTMENT table (pay attention to whether there are these two tables in your database, and whether there is any data in the DEPT table.)

INSERT INTO department SELECT*FROM dept;

Example: Insert records from EMP table into EMPLOYEE table

INSERT INTO user(id,name,age,email)

SELECT id,name,age,email FROM user1;

Simple data query

SELECT * | column name 1, column name 2...]FROM table name WHERE condition; where:

"* means query all columns in the table

WHERE is used to specify query conditions. If not omitted, when the SELECT statement is executed, the system will

First, according to the conditional expression condition of the WHERE clause, the records that satisfy the condition are searched from the basic table specified by the FROM clause, and then the result table is formed according to the target column or target expression in the SELECT clause.

Example: Query the records of all columns in the employee table

SELECT * FROM employee;

Example: Querying the information of some columns of eligible employees

SELECT empno,ename,job,sal,comm

FROM employee

WHERE comm IS NULL;

Data Update

UPDATE table name

SET col_name1=expr1 [,col_name2=expr2 ...][WHERE clause]

illustrate:

set clause: According to the conditions specified in the where clause, modify the data rows that meet the conditions. If the where clause is not set in the statement, all rows are updated.

expr1, expr2... can be constants, variables or expressions. Multiple column values ​​of the data row can be modified at the same time, separated by commas.

Example: Update all data in a table

UPDATE employee SET deptno=50;

Increase the bonus of employees with bonuses in the employee table by 200 yuan

UPDATE employee SET comm=comm+200 WHERE comm IS NOT NULL;

data deletion

DELETE FROM table name[WHERE condition];

Where WHERE specifies the conditions that the deleted records meet, if omitted, all records will be deleted.

example:

Delete all employee data

DELETE FROM employee;

Delete Employee Data No. 1004

DELETE FROM employee WHERE empno=1004;

Note: When the deleted data has a foreign key connection with other tables, it will prompt that the deletion failed. You should delete all records in the foreign key constraint child table first, and then delete the corresponding records in the main table

Data deletion (TRUNCATE)

clear datasheet

TRUNCATE TABLE tablename;

Note: Not only will the entire contents of the table be emptied, but the self-incrementing ID will also start from 0.

Guess you like

Origin blog.csdn.net/qq_46007633/article/details/123946709