Detailed Explanation of MySQL Database Functions and Constraints

Detailed Explanation of MySQL Database Functions and Constraints

MySQL database is a powerful relational database management system that provides rich functions and constraints to process and protect data. This blog will introduce the functions and constraints in the MySQL database in detail, and provide examples to demonstrate their usage.

function

String functions

string concatenation function

CONCAT(str1, str2, ...): Concatenate multiple strings into one string.

Example:

SELECT CONCAT('Hello', ' ', 'World') AS Result;
-- 输出: Hello World

Convert all strings to lowercase

LOWER(str): Converts a string to lowercase.

Example:

SELECT LOWER('Hello World') AS Result;
-- 输出: hello world

Convert a string to all uppercase

UPPER(str): Converts a string to uppercase.

Example:

SELECT UPPER('Hello World') AS Result;
-- 输出: HELLO WORLD

string left padding

LPAD(str, len, padstr): Pad the specified characters on the left side of the string to make its length reach the specified length.

Example:

SELECT LPAD('Hello', 10, '*') AS Result;
-- 输出: *****Hello

string right padding

RPAD(str, len, padstr): Pad the specified characters on the right side of the string to make its length reach the specified length.

Example:

SELECT RPAD('Hello', 10, '*') AS Result;
-- 输出: Hello*****

Remove leading and trailing spaces from a string

TRIM([BOTH | LEADING | TRAILING] trimstr FROM str): Remove the specified characters at the beginning and end of the string (default is space).

Example:

SELECT TRIM('   Hello   ') AS Result;
-- 输出: Hello

String interception

SUBSTRING(str, start, length): Intercept a substring of a string.

Example:

SELECT SUBSTRING('Hello World', 7, 5) AS Result;
-- 输出: World

application

The above are some commonly used string functions, which can help us process and convert string data, such as splicing strings, converting case, filling blanks, etc.

Numeric function

Rounded up

CEILING(x): Returns the smallest integer not less than x.

Example:

SELECT CEILING(3.14) AS Result;
-- 输出: 4

round down

FLOOR(x): Returns the largest integer not greater than x.

Example:

SELECT FLOOR(3.14) AS Result;
-- 输出: 3

Returns the modulus of x/y

MOD(x, y): Returns the remainder of dividing x by y.

Example:

SELECT MOD(10, 3) AS Result;
-- 输出: 1

Seek random numbers

RAND(): Returns a random number between 0 and 1.

Example:

SELECT RAND() AS Result;
-- 输出

: 0.123456789

Round up and keep n decimal places

ROUND(x, d): Round x up to d decimal places.

Example:

SELECT ROUND(3.14159, 2) AS Result;
-- 输出: 3.14

application

Numeric functions are useful for numerical calculations and manipulations. We can use these functions to perform operations such as rounding, rounding, and remainder of values ​​to meet various needs.

date function

return current date

CURDATE(): Returns the current date.

Example:

SELECT CURDATE() AS Result;
-- 输出: 2023-06-23

return current time

CURTIME(): Returns the current time.

Example:

SELECT CURTIME() AS Result;
-- 输出: 12:34:56

return current date+time

NOW(): Returns the current date and time.

Example:

SELECT NOW() AS Result;
-- 输出: 2023-06-23 12:34:56

Get the year of the specified date

YEAR(date): Returns the year of the specified date.

Example:

SELECT YEAR('2022-01-01') AS Result;
-- 输出: 2022

Get the month of the specified date

MONTH(date): Returns the month of the specified date.

Example:

SELECT MONTH('2022-01-01') AS Result;
-- 输出: 1

Get the day of the specified date

DAY(date): Returns the number of days in the specified date.

Example:

SELECT DAY('2022-01-01') AS Result;
-- 输出: 1

Return a time, the date is postponed by number DAY (or MONTH, YEAR)

DATE_ADD(date, INTERVAL number DAY | MONTH | YEAR): Returns the date after the specified date is delayed by a certain time.

Example:

SELECT DATE_ADD('2022-01-01', INTERVAL 1 MONTH) AS Result;
-- 输出: 2022-02-01

The difference in days between two specified times

DATEDIFF(date1, date2): Returns the difference in days between two dates.

Example:

SELECT DATEDIFF('2022-01-01', '2022-01-10') AS Result;
-- 输出: -9

application

Date functions provide functions for manipulating and calculating dates and times. We can use these functions to obtain the current date and time, extract the year, month, and day of the date, and perform date addition and subtraction operations to meet various time-related needs.

flow control function

judge

IF(condition, value_if_true, value_if_false): Judge according to the condition and return the corresponding value.

Example:

SELECT IF(1 < 2, 'Yes', 'No') AS Result;
-- 输出: Yes

If the first value is null, then return the second value, otherwise return the first value

COALESCE(value1, value2, ...): Returns the first non-null value.

Example:



SELECT COALESCE(NULL, 'Hello') AS Result;
-- 输出: Hello

case statement

CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE result END: Branch judgment based on conditions.

Example:

SELECT
    CASE
        WHEN score >= 90 THEN '优秀'
        WHEN score >= 80 THEN '良好'
        WHEN score >= 60 THEN '及格'
        ELSE '不及格'
    END AS Result
FROM
    students;

The above are some commonly used process control functions, which can help us perform operations such as condition judgment, null value processing, and branch selection to meet various complex data processing needs.

constraint

Constraints are rules used to guarantee data integrity and consistency. The MySQL database provides a variety of constraint types, including primary key constraints, unique constraints, and foreign key constraints.

primary key constraint

Primary key constraints are used to identify unique records in a table and ensure the uniqueness of each record in the table.

Example:

CREATE TABLE students (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT
);

unique constraint

A unique constraint is used to ensure the uniqueness of a column value in a table.

Example:

CREATE TABLE employees (
    emp_id INT,
    emp_name VARCHAR(50),
    emp_email VARCHAR(50) UNIQUE,
    ...
);

foreign key constraints

Foreign key constraints are used to associate data in two tables to ensure data consistency.

Example:

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    order_date DATE,
    ...
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

add foreign key

ALTER TABLE orders
ADD FOREIGN KEY (customer_id)
REFERENCES customers(customer_id);

delete foreign key

ALTER TABLE orders
DROP FOREIGN KEY fk_orders_customers;

detection constraints

By defining constraints, you can ensure that the data in your database satisfies expected rules and relationships. If the data does not meet the constraint conditions, an error or warning will be generated to ensure the integrity of the data.

not-null constraint

A not-null constraint is used to restrict the value of a column in a table from being null.

Example:

CREATE TABLE employees (
    emp_id INT PRIMARY KEY,
    emp_name VARCHAR(50) NOT NULL,
    ...
);

sample

The above is an introduction to the functions and constraints commonly used in the MySQL database. Through these functions, we can perform various processing and calculations on the data; while constraints can ensure the integrity and consistency of the data. Reasonable use of functions and constraints can make our database more powerful and reliable.

Summarize

This blog introduces the functions and constraints in the MySQL database, covering the usage and demonstration of string functions, numeric functions, date functions, and process control functions. It also introduces the definitions and definitions of primary key constraints, unique constraints, and foreign key constraints. application. Mastering the use of these functions and constraints can better process and protect the data in the database, and improve the efficiency and accuracy of data operations.

I hope this blog helps you understand the functions and constraints of the MySQL database. If you have any questions or suggestions, please feel free to leave a message, I will reply as soon as possible. thanks for reading!

Guess you like

Origin blog.csdn.net/run65536/article/details/131477119