当前位置:网站首页>MySQL common instructions

MySQL common instructions

2022-06-23 03:37:00 ZNineSun

This article will gradually put all commonly used sql The sentences are listed one by one , It is suitable for most interviews and written examinations , You can also do it yourself in the project , At the same time, this article will Continuous updating , Stay tuned .

1. Capitalize all letters

upper(str)
eg:upper('green')->GREEN

2. Make all letters lowercase

lower(str)
eg:lower('grEEn')->green

3. Connection string ( String splicing )

concat(str1,str2)
eg:concat('aaB','cd')->aaBcd

4. Crop string

#  From a Bit start , extract b Characters ,b If it is not written, it will be intercepted to the last bit by default 
SUBSTRING(str,a,b)
#  Start on the left , extract b Characters 
left(str,b)
#  From the right , extract b Characters 
right(str,b)

5. Get string length

  • length(): Unit is byte ,utf8 Code , A Chinese character has three bytes , A number or letter, a byte .gbk Code , Two bytes of a Chinese character , A number or letter, a byte .
  • char_length(): Unit as character , No matter Chinese character or number or letter, it is a character .
length('ninesun China ')=7+6=13
CHAR_LENGTH('ninesun China ')=7+2=9

6.group_concat() function

There is group by In the query statement of ,select The specified field is either contained in the group by After statement , As a basis for grouping , Or in aggregate functions .

The data in the table is as follows :
 Insert picture description here

We look for people with the same name id, You can query like this :

select name,id from `user` order by name;

 Insert picture description here

You can see that the name has many repetitions , It doesn't look intuitive , So lead to group_concat

  • function : take group by The resulting values in the same group are connected , Returns a string result
  • grammar :group_concat( [distinct] Fields to connect [order by Sort field asc/desc ] [separator ‘ Separator ’] )
  • explain : By using distinct You can exclude duplicate values ; If you want to sort the values in the results , have access to order by Clause ;separator Is a string value , The default is a comma .

So we look up the same name Id, This function can be written like this :

select name,GROUP_CONCAT(id) from `user` GROUP BY name;

 Insert picture description here

Of course, we can also put the above id The numbers are sorted from large to small , And use ’_' As a separator :

select name,GROUP_CONCAT(id ORDER BY id desc SEPARATOR '_') from `user` GROUP BY name;

 Insert picture description here

Title Example :https://leetcode.cn/problems/group-sold-products-by-the-date/submissions/

7.rlike

Contains a character

# ^DIAB1 Include with DIAB1 start 
# .* For any character  \\ Said the blank space 
# .*\\sDIAB1  Any character space DIAB1 start 
conditions rlike '^DIAB1|.*\\sDIAB1';

Be careful rlike You can use regular expressions to match

8.having

mysql in , When we use aggregate functions , Such as sum,count after , When screening conditions are needed again ,having That comes in handy , because WHERE Filter records before aggregation ,having and group by It is used in combination , Of course, it can be different group by Connected use , however having The following fields must be return fields .
Be careful having The final judgment field must be the result returned by the aggregate function
Example :
 Insert picture description here

As shown in the table above , We grouped by age

SELECT id,name,age from user group BY age

 Insert picture description here

Then we need to calculate that the age is greater than or equal to 23 Of

SELECT id,name,age from user group BY age HAVING age>=23

 Insert picture description here

9.union

MySQL UNION Operators are used to connect more than two SELECT The results of a statement are combined into a set of results . Multiple SELECT Statement will remove duplicate data .

For example, the first query has 100 Two columns , The second query result is also 160 Two columns , Therefore, using union all after , You can combine these two results into one , become 260 Row two columns .

Grammar format :

SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
UNION [ALL | DISTINCT]
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

Parameters

  • expression1, expression2, … expression_n: Columns to retrieve .
  • tables: Data table to retrieve .
  • WHERE conditions: Optional , Retrieve conditions .
  • DISTINCT: Optional , Delete duplicate data in result set . By default UNION The operator has removed the duplicate data , therefore DISTINCT Modifiers have little effect on the results .
  • ALL: Optional , Return all result sets , Contains duplicate data .

unin There are many other uses of , Like many interviews, you have to ask : The problem of row to column type is nothing more than the following two steps :

  • One by one : hold “ Name ” As a new column value, Original value Also as a new column , This is a query , Other columns do not
  • use union all Splice the results of each column

Take the following simple question (leeteCode:1795. The price of each product in different stores ) Let's get you started :
Title Description :
 Insert picture description here

Please refactor Products surface , Check the price of each product in different stores , Make the output format change to (product_id, store, price) . If this product is not sold in the store , This line is not output .

In the output result table The order is not required .

Please refer to the following example for query output format .
 Insert picture description here

This problem is a typical row to column problem , Let's follow the steps just mentioned to solve the problem :

  • One by one : hold “ Name ” As a new column value( Topic store), Original value Also as a new column ( Topic price), This is a query , Other columns do not
  • use union all Splice the results of each column

If this product is not sold in the store , This line is not output , So the original column is not null The screening criteria for
So the final code is as follows :

select product_id,'store1' as store,store1 as price
from Products where store1 is not null
union all 
select product_id,'store2' as store,store2 as price
from Products where store2 is not null
union all 
select product_id,'store3' as store,store3 as price
from Products where store3 is not null

Let me explain it in general ’store1’ This is to add a new column , This store1 It will show up in stroe In this column .
 Insert picture description here

If you put store1 Change to another name , Such as store111, The result is :
 Insert picture description here

Seeing this place, you should know the specific usage of row column conversion .

原网站

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