SQL memo (updated from time to time)

concat(),concat_ws(),group_concat()

    concat() : concatenate multiple strings into one string, and return the result as the string generated by the connection parameters. If any parameter is null, the return value is null.

SELECT CONCAT(1,',',2,',',3,',',4) result;

Operation result: 1, 2, 3, 4

SELECT CONCAT(1,',',NULL,',',3,',',4) result;

Operation result: NULL


    concat_ws() : (concat with separator) Same as concat(), concatenate multiple strings into one string, but you can specify the separator at one time. If the separator is null, the result is all null. If the parameter after the separator is null, then null will be skipped.

SELECT CONCAT_WS(',',1,2,3,4) result;

Operation result: 1, 2, 3, 4

SELECT CONCAT_WS(',',1,NULL,3,4) result;

Operation result: 1,3,4

SELECT CONCAT_WS(',',1,2,3,4) result;

Operation result: NULL


    group_concat() : In the group by query statement, concatenate multiple rows of data in the same group into a single string.

Syntax : group_concat([distinct] field to be connected [order by sort field asc/desc] [separator'separator'])
Description : Duplicate values ​​can be excluded by using distinct; if you want to sort the values ​​in the result, you can use The order by clause; separator is a string value, the default is a comma.

Insert picture description here
    Use group_concat() to list each person’s grades with a space as the separator

SELECT `name`,GROUP_CONCAT(mark SEPARATOR ' ') result
FROM score1 GROUP BY `name`;

Insert picture description here
    Use group_concat() to list everyone's grades in the form of key-value pairs

SELECT `name`,GROUP_CONCAT(`subject`,':',mark ORDER BY `subject`) result
FROM score1 GROUP BY `name`;

Insert picture description here
    Note for group_concat() :

  1. After using group_concat, if limit is used in select, it will not work
  2. There is a length limit when connecting fields with group_concat. Use the group_concat_max_len system variable to set the maximum length allowed. SET [SESSION | GLOBAL] group_concat_max_len = val;
  3. The system default separator is comma

COALESCE(),IFNULL()

    COALESCE() is mainly used for null value processing, and its parameter format: COALESCE (expression,value1,value2……,valuen)
    The first parameter expression of COALESCE() function is the expression to be tested, and the following parameters are The number is uncertain.
    The COALESCE() function will return the first non-empty expression in all parameters including expression.
    If expression is not a null value, return expression; otherwise, determine whether value1 is a null value,
    if value1 is not a null value, return value1; otherwise, determine whether value2 is a null value,
    if value2 is not a null value, return value2;
    if all expressions If the formula is null, NULL is returned.

SELECT COALESCE(1,2,3) result1,
COALESCE(NULL,2,3) result2,
COALESCE(NULL,NULL,3) result3;

Operation result: 1, 2, 3

    The COALESCE() function can be used to complete almost all null value processing, but a simplified version of it is provided in many database systems. These simplified versions only accept two variables, such as IFNULL()

SELECT IFNULL(NULL,666) result;

Running result: 666

SUM() calculates multiple columns

Insert picture description here

SELECT *,SUM( Chinese + Math + English ) sum
FROM score2 GROUP BY `name`

Insert picture description here

Column to row and row to column

    Column to row, column to row
Insert picture description here

SELECT `name`,
MAX(IF(`subject`='语文',mark,0)) Chinese,
MAX(IF(`subject`='数学',`mark`,0)) Math,
MAX(IF(`subject`='英语',`mark`,0)) English
FROM score1
GROUP BY `name`;

Insert picture description here


    Row to column, row to column

SELECT `name`,'语文'  `subject`,Chinese mark FROM score2
UNION
SELECT `name`,'数学'  `subject`,Math mark FROM score2
UNION
SELECT `name`,'英语'  `subject`,English mark FROM score2
ORDER BY `name`;

DISTINCT and GROUP BY conversion

    There are tables as follows, id is the record id, user_id is the user id, and counts the number of records and users.
Insert picture description here
    DISTINCT's approach

SELECT COUNT(id) sum_id,COUNT(DISTINCT user_id) sum_user FROM t1;

    The practice of GROUP BY

SELECT sum(sum) sum_id,COUNT(user_id) sum_user FROM (
	SELECT user_id,COUNT(1) sum FROM t1 GROUP BY user_id ) temp;

Insert picture description here

The name of the subquery

    The name of the subquery must be set, if not set, an error will be reported.

Associated subquery and exists subquery

SELECT product_type, product_name, sale_price
FROM product t1 WHERE sale_price > (
    SELECT avg(sale_price) FROM product t2
     WHERE t1.product_type = t2.product_type);

    The execution logic is as follows:
(1) Execute the outer loop first, then take the first value of the product _type column, enter the subquery, judge the where clause conditions, and if it matches, calculate the average value and return the result.
(2) Repeat the above operation until all records in the product _type column of the Product table in the main query are retrieved.

    Find out the data in the article table, but the uid must exist in the user table. The SQL statement is as follows:

SELECT * FROM article WHERE EXISTS (
SELECT * FROM user WHERE article.uid = user.uid);

    Put the data of the main query into the subquery for conditional verification, and determine whether the data result of the main query can be retained according to the verification result (TRUE or FALSE, so select can be arbitrary).

like matches special characters

    escape can specify what the escape character used in like is, and the character after the escape character will be regarded as the original character

select * from table where name like '1\_%' escape '\'

select * from table where name like '%\%%' escape '\'

Guess you like

Origin blog.csdn.net/H_X_P_/article/details/107233245