当前位置:网站首页>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 :
We look for people with the same name id, You can query like this :
select name,id from `user` order by name;

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;

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;

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 :
As shown in the table above , We grouped by age
SELECT id,name,age from user group BY age

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

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 :
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 .
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 .
If you put store1 Change to another name , Such as store111, The result is :
Seeing this place, you should know the specific usage of row column conversion .
边栏推荐
- Goframe framework: log configuration management
- On the way home from the Spring Festival transportation, traffic visualization will escort you
- JSON. Function of the stringify() optional parameter
- Analysis on the development of China's satellite navigation industry chain in 2021: satellite navigation is fully integrated into production and life, and the satellite navigation industry is also boo
- Enterprise official website applet building tutorial
- The MIUI 13 development version of Xiaomi mobile phone blocks the chrome application and cannot be opened after installation
- Configuring multi cluster management using kubectl
- What are the advantages of the completely free and open source flutter? How to learn about flutter?
- Frequent actions to expand the scale of new energy industry Guangzhou plans to invest 1.4 billion in photovoltaic power generation projects
- 数据加密技术之源代码加密
猜你喜欢

第一批00后下场求职:不要误读他们的“不一样”

R tree of search tree

【owt】owt-client-native-p2p-e2e-test vs2017构建2 :测试单元构建及运行

【曾书格激光SLAM笔记】Gmapping基于滤波器的SLAM

LRU cache

直接插入排序
![Analysis on the development prospect of China's brain computer interface industry in 2021: wide application prospect, sustained and rapid growth of market scale [figure]](/img/84/192d152ceb760264b6b555b321f129.jpg)
Analysis on the development prospect of China's brain computer interface industry in 2021: wide application prospect, sustained and rapid growth of market scale [figure]

Google Earth Engine(GEE)——长时间序列逐月VCI数据提取分析和面积计算(墨西哥为例)
![Analysis of China's integrated circuit industry chain in 2021: huge downstream market demand [figure]](/img/de/d73805aaf4345ca3d2a7baf85aab8d.jpg)
Analysis of China's integrated circuit industry chain in 2021: huge downstream market demand [figure]
![[OWT] OWT client native P2P E2E test vs2017 build 2: test unit construction and operation](/img/b0/4ea8069a88ce19ca7dbfa67ac9fcba.png)
[OWT] OWT client native P2P E2E test vs2017 build 2: test unit construction and operation
随机推荐
An implementation of warning bombing
数据加密技术之源代码加密
How to print array contents
【owt】owt-client-native-p2p-e2e-test vs2017构建2 :测试单元构建及运行
Analysis on development history, industrial chain, output and enterprise layout of medical polypropylene in China in 2020 [figure]
What is the difference between the poll () method and the remove () method?
The compatibility of remotefx schemes is related to multiple factors
How to get started with apiccloud app and multi terminal development of applet based on zero Foundation
Quickly understand the development status of secondary nodes of industrial Internet identity analysis
Chapter IV open source projects and deployment
Get method of fetch request and data of formdata type submitted by post
Tcapulusdb Jun · industry news collection (III)
[metauniverse 7ai rope skipping] how is this app light application realized? What are the application scenarios?
Goframe framework: log configuration management
JS Part 4
On the way home from the Spring Festival transportation, traffic visualization will escort you
Using jhipster to build microservice architecture
直接插入排序
What about the high cost of storage system? The original computer room can save so much money!
Analysis on demand and market scale of China's steamed stuffed bun industry in 2020 [figure]