SQL functions and advanced statements

Table of contents

 

1. Commonly used functions

1. Aggregate functions

2. Mathematical functions

3. String functions

Two, sql advanced statement

1. SELECT (display the specified field or all records in the table)

2.DISTINCT (Do not display records with repeated data in the specified field) 

3.WHERE (specified condition query)

4. AND, OR (condition and, or)

5.IN (display the data record for the value specified by the field)

6.BETWEEN...AND... (display the data records within the two value range specified by the field)

7. Wildcards (often used in like patterns)

8. LIKE (find records in the specified pattern range)

9.ORDER BY (sort by keyword)

10. GRUOP BY (summarize and group the query results of the fields behind GROUP BY)

11.HAVING (used to filter the recordset returned by the GROUP BY statement, usually used in conjunction with the GROUP BY statement)

12. Alias ​​(field alias, table alias)

13. Subquery (join tables, insert another sql statement in WHERE clause or HAVING clause)

14.EXISTS (used to test whether the inner query has produced any results)

15. Table connection (inner connection, left connection, right connection)

16. CREATE VIEW (view can be regarded as a virtual table or stored query)

17.UNITON (union, combine the results of two SQL statements)

18. The difference between empty value (NULL) and no value (' ')

19.CASE (is a keyword used by sql as a logical judgment such as if then else)

20. Regular (use regular expressions to query content)

21. Stored procedure (a stored procedure is a set of SQL statements to complete a specific function)

(1) Create and use

(2) View stored process information

(3) View stored procedure creation information

(4) Delete the stored procedure

(5) Creation and use of stored procedures with parameters


 

1. Commonly used functions

1. Aggregate functions

average price 

The number of entries that are not a field

All log entries

Number of Deduplicated Record Entries

max min price 

sum of prices 

2. Mathematical functions

Function name use
abs(x) returns the absolute value of x
rand() Returns a random number between 0 and 1
mod(x,y) Returns the remainder after dividing x by y
power(x,y) Return x raised to the yth power
round(x) returns the integer closest to x
round(x, y) Keep the rounded value of x to y decimal places
sqrt(x) returns the square root of x
truncate (x, y) Returns the value of the number x truncated to y decimal places
ceil(x) Returns the smallest integer greater than or equal to x
floor(x) Returns the largest integer less than or equal to x
greatest(x1,x2,...) Returns the largest value in the collection, and can also return the largest value of multiple fields
least(x1,x2,...) Returns the smallest value in the collection, and can also return the smallest value of multiple fields

3. String functions

concatenate string 

 If there is PIPES_AS_CONCAT in the sql module, you can also use || to splice strings

intercept string

replace string 

Strip the beginning and end of a string

Two, sql advanced statement

The following two tables are used for the demonstration of sql advanced statements

Product list

Commodity classification table

1. SELECT (display the specified field or all records in the table)

SELECT `field name` FROM `table name`;

                     * represents all fields

2.DISTINCT (Do not display records with repeated data in the specified field) 

SELECT DISTINCT `field name` FROM `table name`;

3.WHERE (specified condition query)

 SELECT * FROM `table name` WHERE conditional expression;

4. AND, OR (condition and, or)

SELECT * FROM `table name` WHERE condition 1 [AND condition 2] [OR condition 3];

5.IN (display the data record for the value specified by the field)

SELECT * FROM `table name` WHERE `field name` [NOT] IN ('value 1', 'value 2'); 

6.BETWEEN...AND... (display the data records within the two value range specified by the field)

SELECT * FROM `table name` WHERE `field name` BETWEEN 'value 1' AND 'value 2';

7. Wildcards (often used in like patterns)

% A percent sign means zero, one or more characters

_ An underscore represents a single character

8. LIKE (find records in the specified pattern range)

SELECT * FROM `table name` WHERE `field name` LIKE 'wildcard pattern';

9.ORDER BY (sort by keyword)

SELECT * FROM `table name` [WHERE conditional expression] ORDER BY `field` [ASC / DESC];

                                                                                              ASC in ascending order (default if not added)

                                                                                           DESC Sort in descending order

10. GRUOP BY (summarize and group the query results of the fields behind GROUP BY)

        It is usually used in combination with aggregate functions. All fields that appear after GROUP BY must appear after SELECT; all fields that appear after SELECT and do not appear in aggregate functions must appear after GROUP BY.

SELECT `field name` [aggregation function (`field name`)] FROM `table name` GROUP BY `field name`;

11.HAVING (used to filter the recordset returned by the GROUP BY statement, usually used in conjunction with the GROUP BY statement)

        The existence of the HAVING statement makes up for the deficiency that the WHERE keyword cannot be used in conjunction with aggregate functions.

SELECT `field name` [aggregation function (`field name`)] FROM `table name` GROUP BY `field name` HAVING condition;

12. Alias ​​(field alias, table alias)

SELECT [table alias.] `field name` [AS] field alias FROM `table name` [AS] table alias;

13. Subquery (join tables, insert another sql statement in WHERE clause or HAVING clause)

 SELECT `field 1` FROM `table 1 name` WHERE `field 2` [comparison operator] ( SELECT `field 1` FROM `table 2 name` WHERE conditional expression);

Comparison operators: Operators that can be symbols, such as =, >, <, >=, <=; operators that can also be literals, such as LIKE, IN, BETWEEN.

14.EXISTS (used to test whether the inner query has produced any results)

        If there is, the system will execute the sql statement in the outer query; if not, the entire sql statement will not produce any results.

15. Table connection (inner connection, left connection, right connection)

Inner join (inner join): returns only rows with equal join fields in the two tables;
left join (left join): returns records including all records in the left table and records with equal join fields in the right table;

right join (right join): Returns all records including all records in the right table and records with equal join fields in the left table.

SELECT * FROM `Table 1 name` A INNER JOIN `Table 2 name` B ON A.`field`=B.`field`; 

         `Fields`... LEFT JOIN

                                             RIGHT JOIN

16. CREATE VIEW (view can be regarded as a virtual table or stored query)

        The difference between a view and a table is that the table actually stores data records, while the view is a structure built on the table, and it does not actually store data records. Temporary tables disappear automatically after the user logs out or the connection to the database is disconnected, but the view does not disappear.

        A view does not contain data, only its definition is stored, and its use generally simplifies complex queries. For example, if you want to perform join query on several tables, and perform operations such as statistical sorting, it will be very troublesome to write SQL statements. Using a view to join several tables, and then querying this view is the same as querying a table. Same, very convenient.

Create and view view tables 

CREATE VIEW view table name AS SELECT statement;

use view table

17.UNITON (union, combine the results of two SQL statements)

        The fields generated by the two SQL statements need to be of the same data record type;

        The data record values ​​generated by UNION will not be duplicated, and will be sorted according to the order of the fields;

        UNION ALL lists all data record values ​​that produce results, with or without duplicates.

SELECT statement 1 UNION [ALL] SELECT statement 2; 

18. The difference between empty value (NULL) and no value (' ')

The length of no value is 0, which does not take up space; while the length of NULL value is NULL, which takes up space.

IS NULL or IS NOT NULL is used to judge whether the field is NULL, and cannot find out whether it has no value.

Use =' 'or <>' 'to handle the judgment of no value. <> represents not equal to.

When using count() to specify the number of rows in the field statistics, if a NULL value is encountered, it will be automatically ignored, and if no value ' ' is encountered, it will be added to the record for calculation.

19.CASE (is a keyword used by sql as a logical judgment such as if then else)

SELECT `field 1`,...,CASE (`judgment field`)

        WHEN condition 1 THEN result 1 //The condition can be a value or a formula

        WHEN condition 2 THEN result 2

[ELSE] result n //ELSE clause is not required

END

FROM `TableName`;

20. Regular (use regular expressions to query content)

SELECT `field` FROM `table name` WHERE `field` REGEXP 'regular expression';

21. Stored procedure (a stored procedure is a set of SQL statements to complete a specific function)

        In the process of using the stored procedure, common or complex work is written in advance using SQL statements and stored with a specified name. This process is compiled and optimized and stored in the database server. When you need to use the stored procedure, you only need to call it. Stored procedures are faster and more efficient than traditional SQL in execution.

Advantages of stored procedures

        After one execution, the generated binary code will reside in the buffer to improve execution efficiency;

        The set of SQL statements plus control statements has high flexibility; it
        is stored on the server side, and the network load is reduced when the client calls it;
        it can be called repeatedly and can be modified at any time without affecting the client call;
        it can complete all database operations , which also controls access to information in the database.

(1) Create and use

--修改结束符为 $$--
delimiter $$

--创建存储过程--
create procedure proc1()
    -> begin
    -> insert into `goods` values ('可乐',3.5,'广州');
    -> delete from `goods` where `gname`='可乐';
    -> end$$

--将结束符修改回 ;--
delimiter ;

--使用存储过程--
call proc1;

(2) View stored process information

(3) View stored procedure creation information

(4) Delete the stored procedure

DROP PROCEDURE [IF EXISTS] `stored process name`;

(5) Creation and use of stored procedures with parameters

Incoming parameter IN

outgoing parameter OUT

Pass in and out parameters INOUT at the same time

Guess you like

Origin blog.csdn.net/wlc1213812138/article/details/131787597