当前位置:网站首页>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)
边栏推荐
- 开源汇智创未来 | 2022开放原子全球开源峰会 openEuler 分论坛圆满召开
- SM整合原来这么简单,步骤清晰(详细)
- Apache POI实现Excel导入读取数据和写入数据并导出
- JS daily question (10)
- Sparksql inserts or updates in batches and saves data to MySQL
- 优炫数据库启动失败,报网络错误
- The most comprehensive promotion plan for the launch of new products
- 【微信小程序】swiper滑动页面,滑块左右各露出前后的一部分,露出一部分
- [file download] easyexcel quick start
- AUTOSAR from introduction to proficiency 100 lectures (78) -autosar-dem module
猜你喜欢
[wechat applet -- solve the alignment problem of the last line of display:flex. (discontinuous arrangement will be divided into two sides)]
使用Jstack、Jconsole和jvisualvm进行死锁分析
excel怎么设置行高和列宽?excel设置行高和列宽的方法
pytorch学习笔记
1 sentence of code, get asp Net core binds multiple sources to the same class
Traffic flow prediction pit climbing record (I): traffic flow data set, original data
How does WPS take quick screenshots? WPS quick screenshot method
Unity Metaverse(三)、Protobuf & Socket 实现多人在线
ODOO开发教程之透视表
带你搞懂 Kubernetes 集群中几种常见的流量暴露方案
随机推荐
AttributeError: ‘module‘ object has no attribute ‘create_ connection‘
Force deduction ----- sort odd and even subscripts respectively
How to add a map to the legendary server
怎样监测微型的网站服务
网安学习-内网安全1
Live in small private enterprises
学习数据库的第一个程序
深度学习刷SOTA的一堆trick
js(forEach)出现return无法结束函数的解决方法
Use annotation test in idea
Un7.28: common commands of redis client.
Use openmap and ArcGIS to draw maps and transportation networks of any region, and convert OMS data into SHP format
2021-10-11
Five correlation analysis, one of the most important skills of data analysts
Jackson解析JSON详细教程
WPS insert hyperlink cannot be opened. What should I do if I prompt "unable to open the specified file"!
What if excel is stuck and not saved? The solution of Excel not saved but stuck
How to monitor micro web services
Unity metaverse (III), protobuf & socket realize multi person online
如何让照片中的人物笑起来?HMS Core视频编辑服务一键微笑功能,让人物笑容更自然