当前位置:网站首页>Functions in MySQL statements
Functions in MySQL statements
2022-07-29 05:10:00 【nianyuw】
Mysql Functions in statements
MySQL The functions in are mainly divided into the following four categories : String function 、 Numerical function 、 Date function 、 Flow function .
1 String function
MySQL There are many built-in string functions , The common ones are as follows :

give an example
-- concat : String splicing
select concat('Hello' , ' MySQL');
-- lower : All lowercase
select lower('Hello');
-- upper : Capitalize all
select upper('Hello');
-- substring : Intercept substring
select substring('Hello MySQL',1,5);
-- lpad : padding-left Due to changes in business requirements , Employee's job number , Uniform for 5 digit , Not enough at present 5 All digits are filled in the front 0.
update emp set workno = lpad(workno, 5, '0');
2 Numerical function
Common numerical functions are as follows :

give an example
-- ceil: Rounding up
select ceil(1.1);
-- round: rounding
select round(2.344,2);
-- rand: Get random numbers
select rand();
-- Through the functions of the database , Generate a six digit random verification code . The random number can be obtained by rand() function , But the random number obtained is in 0-1 Between , So you can multiply it by 1000000, Then discard the decimal part , If the length is not enough 6 position , repair 0
select lpad(round(rand()*1000000 , 0), 6, '0');
3 Date function
Common date functions are as follows :

give an example
-- curdate: The current date , fit date Type data
select curdate();
-- curtime: current time
select curtime();
-- now: Current date and time , fit datetime type
select now();
insert into t_user(create_time) values (now())
-- YEAR , MONTH , DAY: The current year 、 month 、 Japan , It can be used to intercept time
select YEAR(now()); select MONTH(now()); select DAY(now());
-- date_add: Increase the specified time interval
select date_add(now(), INTERVAL 70 YEAR );
-- datediff: Get the number of days between the two dates , Can cooperate with now() perhaps curdate To get the time difference
select datediff('2021-10-01', '2021-12-01');
-- Query the enrollment days of all employees , And sort them in reverse order according to the number of days of employment .
select name, datediff(curdate(), entrydate) as 'entrydays' from emp order by entrydays desc;
4 Flow function
Flow function is also a kind of commonly used function , Can be in SQL Statement to implement conditional filtering , So as to improve the efficiency of statements .

give an example
ifnull The first value is null, The value is the second
-- if
select if(false, 'Ok', 'Error');
-- ifnull The first value is null, The value is the second
select ifnull('Ok','Default');
select ifnull('','Default');
select ifnull(null,'Default');
-- case when then else end It is often used to judge the grade
-- demand : Inquire about emp Name and working address of the employee on the form ( Beijing / Shanghai ----> first-tier cities , other ----> Second-tier cities )
select
name,
( case workaddress when ' Beijing ' then ' first-tier cities ' when ' Shanghai ' then ' first-tier cities ' else ' Second-tier cities ' end ) as ' Work address '
from emp;
select
id, name,
(case when math >= 85 then ' good ' when math >=60 then ' pass ' else ' fail, ' end ) ' Math grades ',
(case when english >= 85 then ' good ' when english >=60 then ' pass ' else ' fail, ' end ) ' English grade ',
(case when chinese >= 85 then ' good ' when chinese >=60 then ' pass ' else ' fail, ' end ) ' Chinese grades '
from score;
5 Other functions
Add some functions used by the landlord in the actual development
- GROUP_CONCAT(str): Grouping string splicing , And Use together in groups
Case study : Query enterprise information and enterprise classification information , Among them, the relationship between enterprise classification information and enterprise is many to many , Query according to the common joint table , We will find that one piece of enterprise information corresponds to multiple enterprise classifications , Multiple records will appear . If you want to classify different enterprises of the same enterprise into one record , You can consider using it GROUP_CONCAT, This function will splice multiple pieces of data onto one piece of data ( String segmentation is used by default )
select
t_enterprise.*,
GROUP_CONCAT(DISTINCT dic_enterprise_category.name) as enterpriseCategoryNames,
dic_operation_status.name as operationStatusName,
dic_region.name as regionName
from t_enterprise
left join ref_enterprise_category
on t_enterprise.id = ref_enterprise_category.enterprise_id
left join dic_enterprise_category
on dic_enterprise_category.id = ref_enterprise_category.category_id
left join dic_operation_status
on t_enterprise.operate_status_id = dic_operation_status.id
left join dic_region
on t_enterprise.region_id = dic_region.id
GROUP BY id

- FIELD(str,str1,str2,str3): among str Is the field name , It can be done to SQL The result set of the query Sort in the specified order , Field str Press str1,str2,str3 Returns the query result set in the order of
Case study : The result of the query will be pushed to the status (0: normal 1: Youtui 2: Off the shelf ) Push by priority , normal , Off shelf sorting , If the status is the same, it will be updated in descending order
select Query data from The query table where Query criteria order by FIELD(push_status,1,0,2)
边栏推荐
- Lenovo Savior r7000+ add ssd+ copy and partition the information of the original D disk to the new SSD
- 网安学习-内网安全1
- Conv2d of torch
- Climbing the pit of traffic flow prediction (II): the simplest LSTM predicts traffic flow using tensorflow2
- How to solve the problem of configuring the progress every time Office2010 is opened?
- Deadlock to be resolved
- TMUX essays
- 那个准时上下班,从不愿意加班加点的人,在我前面升职了...
- 开源汇智创未来 | 2022开放原子全球开源峰会 openEuler 分论坛圆满召开
- [config] configure array parameters
猜你喜欢

< El table column> place multiple pictures

Open source Huizhi creates the future | the openeuler sub forum of 2022 open atom global open source summit was successfully held

How to monitor micro web services

让你的正则表达式可读性提高一百倍

向往的开源之多YOUNG新生 | 从开源到就业的避坑指南来啦!

Introduction of JDBC preparestatement+ database connection pool

Climbing the pit of traffic flow prediction (III): using pytorch to realize LSTM to predict traffic flow

Un7.28: common commands of redis client.

Climbing the pit of traffic flow prediction (II): the simplest LSTM predicts traffic flow using tensorflow2

Using jupyter (I), install jupyter under windows, open the browser, and modify the default opening address
随机推荐
TCP three handshakes and four waves
What if the computer cannot open excel? The solution of Excel not opening
Sparksql inserts or updates in batches and saves data to MySQL
The representation of time series analysis: is the era of learning coming?
让你的正则表达式可读性提高一百倍
[wechat applet] swiper slides the page, and the left and right sides of the slider show part of the front and back, showing part of the front and back
Introduction of JDBC preparestatement+ database connection pool
开区网站打开自动播放音乐的添加跟修改教程
How does excel filter out the content you want? Excel table filtering content tutorial
Use openmap and ArcGIS to draw maps and transportation networks of any region, and convert OMS data into SHP format
How is the entered query SQL statement executed?
传奇如何一台服务器配置多个版本微端更新
stack和queue和优先级队列(大堆和小堆)模拟实现和仿函数讲解
P2181 diagonal
WPS insert hyperlink cannot be opened. What should I do if I prompt "unable to open the specified file"!
How to solve the problem of configuring the progress every time Office2010 is opened?
传奇服务端如何添加地图
开源汇智创未来 | 2022开放原子全球开源峰会 openEuler 分论坛圆满召开
Young freshmen yearn for more open source | here comes the escape guide from open source to employment!
Use annotation test in idea