Common database functions - basics

Common database functions - basics

Insert image description here

Common functions

1. Statistical function-count

count will count how many rows there are in our table and return our number of rows


-- MySQL的统计函数的使用 函数可以自己去写 也可以自定义函数 
-- 1.统计一个班有多少学生
SELECT COUNT(*) FROM student;-- 就是表有多少行就返回多少个学生!!!
-- 统计数学成绩大于90分的同学有多少
SELECT COUNT(*) FROM student 
	WHERE (math>90);
-- count  就是要求和
-- count* 是返回满足条件的记录的总行数
-- count (列)统计满足条件的某列有多少个,但是会排除null的情况 就是这两个基本没差别
2.sum function

The sum function is a simple summation

Use commas to separate multiple summation statements for processing.

-- sum 统计返回满足where 条件某一行的和
-- 统计一个班级语文,英语,数学各科的总成绩
SELECT SUM(math) FROM student; -- 这个就会统计全班的成绩进去
-- 各科的总成绩
SELECT SUM(math),SUM(english),SUM(chinese) FROM student;
-- 统计总分的总和
SELECT SUM(math+english+chinese) FROM student;
3.avg function

This function is a function that calculates the average. The specific operation of this function is to find the average value of a certain data we specify in our table.


SELECT AVG(chinese) FROM student;-- 这个就是对数学成绩进行求平均分
要是想求不同数据的平均值我们就直接从avg里面进行修改一下就行
-- 这个是利用我们的求和进行模拟的一个函数 其实我们后期是可以自己写函数的 这样也就是增强我们的查询速度
-- 统计一个班的语文平均分 我们先求出这个班的总成绩 然后除以总和就是我们的平均分的操作处理
SELECT SUM(chinese)/COUNT(*) FROM student;
-- sum函数仅仅对数值有用 不要对数值进行求和处理
4.max min function

This is the operation of finding the maximum or minimum value of a certain data in the entire table.



-- 求班级最高分 或者最低分
SELECT MAX(math+english+chinese),MIN(math+english+chinese)
FROM student;
5. String functions
1. Several commonly used string functions (the red ones are used more frequently and need to be mastered)

Insert image description here

1.charset()

This function returns the character set of our currently selected field.

-- 
SELECT CHARSET(ename) FROM emp;-- 这个ename是代表我们要查看的字段是什么样的
2.concat()

String splicing is also very simple. It means splicing multiple data, which is very similar to string splicing in Java.

-- 格式化查询 

-- 这个是当作一列进行返回的,连接字符串,将多个列放到同一行
SELECT CONCAT(ename,' 的工作是',job) FROM emp; -- 这个插入图片展示 就是我们可以格式化的显示

Insert image description here

3.instr

The parameter passed in this function here is where the second string appears for the first time.

SELECT INSTR("yt1105","1") FROM DUAL; -- 这个dual就是一个很小的表 这个表就是我们没表可以用的时候我们就可以用系统给我们的表

Here we use the dual table. This table is assigned to us by the system and is called the sub-yuan table. It can be used as a test table.

Also, please note that the subscripts of the arrays in the database start from 1.

4.lcase ucase conversion

That is, the case conversion operation

-- 转成大写或者是小写
-- low upper 的转换 
SELECT LCASE(ename) FROM emp;
这个可以将我们的数据进行转化小写
5.left

This function has two parameters. The first is the position you want to take, and the second is how many parameters you want to take.

-- 这个就是从左边取出来一些数据出来 2代表是取出几个
SELECT LEFT(ename,2) FROM emp;

Insert image description here

Looking at the picture to tell the truth, we will take out our first two digits, that is, take out 2 digits from the left

6.length
-- 这个是按照字节进行返回的 
SELECT LENGTH(ename) FROM emp;  -- 这个是去统计到底是每一个长度是多少这个是返回字节


Since the number of bytes is returned, it will be related to our character set. Our utf8 is Chinese characters corresponding to 3 bytes.

7.replace

-- 如果是mannager就替换成经理我们从工作里面找的
SELECT ename,REPLACE (job,'MANAGER','经理') FROM emp;

This function will replace the data we want to replace with the data we want
Insert image description here

It’s obvious when you look at the picture.

8.strcmp

This is to compare whether two strings are the same. If so, return 0. Otherwise, return a positive or negative number based on the size relationship.


SELECT STRCMP('hh','hh')FROM DUAL;-- 这个就是如果相同就会返回0 不然就会返回其他数据
-- 注意是不是大小写的区分
9.substring

Operation processing of intercepting strings

-- substring 用来截取字符串的
SELECT SUBSTRING(ename,1,2) FROM emp;-- 这句话是返回ename这个列从第一个位置开始取出2个字符

The first parameter represents where I want to intercept, and the following is the number from which to intercept.

10 ltrim,rtrim,trim (understand)

This is the operation of removing spaces on the left, spaces on the right, and spaces on the left and right.


-- 
SELECT LTRIM('    asdsadsda') FROM DUAL;-- 进行图片演示

SELECT RTRIM('sadsads      ') FROM DUAL;-- 进行图片演示

SELECT TRIM('   ada    adsa   ') FROM DUAL;
small exercise

The first employee name displayed is converted to lowercase, and the rest remain unchanged.

Insert image description here

parse



-- 不断进行套娃就行 以首字母小写的方式显示所有员工emp表的姓名
-- 先取出ename的第一个字符取出,转成小写的,把他后面的字符串取出进行拼接输出
-- substring如果第三个参数什么都不写的话 就会导致我们会默认取到最后
SELECT CONCAT(LCASE(SUBSTRING(ename,1,1)),SUBSTRING(ename,2,LENGTH(ename)))FROM emp;
6. Mathematical functions
1 Introduction

Insert image description here

1.abs() absolute value function
-- 演示数学函数
SELECT ABS(-110) FROM DUAL;
2.ceiling

Ceiling function operations

SELECT BIN(10) FROM DUAL;  --  配图片
-- ceiling 天花板 就是向上取整
3.floor rounding down operation
SELECT FLOOR(1.2) FROM DUAL;-- 这个dual 是一个亚元表 
4.conv

Convert your data from a certain base to the base you want

SELECT CONV(1221,10,2) FROM DUAL; -- 从10进制准换为2进制
-- 第一个是表明你要将这个数据准化为什么进制
-- 第一个数 是你指定的数据 然后第二数据是你认为这个数据是什么数,然后第三个数据代表你要将这个数据转化为什么数据

Insert image description here

5.format

This function converts the decimal part we want to process into the number of digits we want to retain

-- 截图
SELECT FORMAT(12111.1212121,2) FROM DUAL;-- 你决定保留几位小数 这个系统会四舍五入 这个会科学计数法
6.least
SELECT LEAST(1,2,21,21,1,2121,-121) FROM DUAL;
-- 求一群数据中的最小值
7.mod
SELECT MOD(10,3) FROM DUAL;-- 这个就是 10%3 的操作处理
8.rand()

-- rand 这个是返回一个随机数值
-- 这个数据放进去之后是种子 但是随机数如果是想要固定的话 我们就给一个具体的数据放进去就行 只要是固定的 那么就不会发生改变
SELECT RAND() FROM DUAL;-- 0~1
7. Time-related functions

Insert image description here

1. Check some time
SELECT CURRENT_DATE FROM DUAL; 2022-01-28

SELECT CURRENT_TIME FROM DUAL; 17:18:40

SELECT CURRENT_TIMESTAMP FROM DUAL; 2022-01-281 7:18:40
2.Use of date_add, date_sub and NOW functions

You can put 2 parameters in it. The first parameter represents the parameter you want to process. The second parameter represents the time to be added or subtracted. The unit can be hours, minutes, seconds, years, months, and days.

Add keyword interval

The operation of the now function is to return the current time including the year, month, day, hour, minute and second. now will calculate the year, month, day, hour, minute and second.

CREATE TABLE mes(
	id INT ,
	content VARCHAR(30),
	send_time DATETIME);
-- 添加一条记录
INSERT INTO mes VALUES(1,'北京新闻',CURRENT_TIMESTAMP);
-- 这个时间函数可以进行的是返回某时某分某秒的操作处理
INSERT INTO mes VALUES(2,'上海新闻',NOW());-- 这个now是返回当前的日期加时间
INSERT INTO mes VALUES(3,'广东新闻',NOW());
SELECT * FROM mes;
-- 1.显示所有的新闻信息,发布日期只显示日期,不用显示时间
SELECT id ,content,DATE(send_time) FROM mes;-- 有种格式话的感觉
-- 请查询在10min中内发布的新闻
SELECT * FROM mes 
	WHERE DATE_ADD(send_time,INTERVAL 10 MINUTE)>=NOW()-- 这个时间加上10min 还是不如滴
	-- 
	SELECT * FROM mes
	WHERE DATE_SUB(NOW(),INTERVAL 10 MINUTE)<=send_time;-- 第一个参数是减数 第二个参数是被减数
3.datediff

This function is used to calculate the number of days between our data.


-- 求一下2011 -11 -11和 1990 -1-1他们之间差了多少天
SELECT DATEDIFF('2011-11-11','1990-01-01') FROM DUAL; 
Small case 1, - Calculate how many days you have lived

-- 用mysql计算你活了多少天
SELECT DATEDIFF(NOW(),'2003-11-05')/365 FROM DUAL;
Small case 2

-- 如果 你能活80岁,求你还能活多少天
-- 1.你要求出 你活到80岁的时候是什么日期
-- 2.然后使用这个datediff求出来和现在进行相减
-- 这个年月日 时分秒都是可以的
-- 这个datediff返回的是相差的时间
SELECT DATEDIFF( DATE_ADD('2003-11-05',INTERVAL 80 YEAR),NOW()) FROM DUAL;
4.timediff

This is the difference calculation of time, which is the calculation between hours, minutes and seconds.


SELECT TIMEDIFF ('10:11:11','2:02:11');-- 这个是进行时间的差值处理操作
-- 
5. Forced type conversion

SELECT YEAR (NOW()) FROM DUAL;

SELECT MONTH(NOW())FROM DUAL;
-- 有种强制类型转换的感觉

After this statement is written, only the year or month will be displayed.

6.UNIX_TIMESTAMP

This will return a number of seconds from 1970-01-01-00-00-00

-- 这个是返回一个秒数 从1970 到现在的时间 
SELECT UNIX_TIMESTAMP FROM DUAL; -- 1970 1 1  这个是返回我们的时间戳的时间是多少时间 从1970年开始的秒数
7.FROM_UNIXTIME

This is to add the number of seconds to the start time of our timestamp, and then decide how we should output this format according to our users.


SELECT FROM_UNIXTIME(112312313,'%Y-%m-%d %H:%i:%s') FROM DUAL;
-- 这个是可以将一个秒数转成一个指定的格式 这个我上边写的格式 是我们自己写的 在开发中可以存放一个数值或者一个整数
-- 这个格式返回的是年月日
-- 实际开发中 我们会使用int来保存一个Unix的时间戳,然后再使用from_unixtime()进行转换,还是很有实用价值的
8. Encryption functions and system functions
1.USER()

This function returns the IP address of our username

SELECT USER() FROM DUAL; -- 这个可以返回的是用户@ip地址 这里由于是一个人进行登陆的 但是由于我们是一个人进行登陆的 所以说
-- 要是有用户进行远程操控 那么我们就会从远程进行获取到对方的ip地址和用户名了

Insert image description here

2.SELECT DATABASE() FROM DUAL;

Show which database we are currently in


SELECT DATABASE() FROM DUAL;

Insert image description here

3. Encryption function md5
-- md5 对用户密码的加密
-- root 不能存放明文 而是加密后的密码
SELECT MD5('root') FROM DUAL;-- 及时被攻破也是很久以前 其实还是很安全的

Insert image description here

After encryption through this function, no matter how long your password is, it will be encrypted to a length of 32 bits.

4.mysql comes with the encryption function PASSWORD

This and md5 are also born due to encryption, but the encryption algorithms are different, resulting in different results.

Just know it

SELECT PASSWORD('root') FROM DUAL;-- 这个算法处理得到的结果又是不同于md5的 
9. Use of process control functions

Insert image description here

1. Task-driven, it requires querying the emp table. If column is null, 0.0 is displayed.

2. If the job in the emp table is clerk, the employee will be displayed. If it is manager, the manager will be displayed. Others will be displayed normally.

When you see this, you feel that there seems to be an if else statement. In fact, it is like this. It does have an if else feeling.

It just becomes when then here

1.if


SELECT IF(TRUE,1,2) FROM DUAL; -- 这个就是说  如果表达式为真 返回第一个否则返回第二个

2.ifnull

SELECT IFNULL(NULL,'hello');-- 如果第一个不为空就返回第一个 否则返回第二个

3.when then operation

SELECT CASE 
	WHEN TRUE THEN 'jack'
	WHEN TRUE THEN 'tom'
	ELSE 'marry' END;-- 如果返回一个成功就不会继续返回下面的了

Implement the second task driver

SELECT ename,(SELECT CASE
		WHEN job='CLERK' THEN '职员'
		WHEN job='MANAGER' THEN '经理'
		WHEN job='SALESMAN' THEN '销售人员'
		ELSE job END) AS 'job'
		FROM emp;		
	-- 这个就是当我们需求需要的时候可以这样操作
	-- 可以理解为select语句后面的,就是我们要显示的,这样就是要表示显示两列,
	-- 第二列经过条件判断进行的操作其实是进行了一个类似于多个并列的if语句
	-- when then

Group statistics

Small case 1.

First introduce our data table

Insert image description here

Let’s briefly talk about what group statistics is. It can be called group calculation. My personal understanding is that we assume that in a department, we are divided into

There are 3 groups numbered 10 20 30, and there are more than 100 people in them. These people belong to these groups, which means that the number of these people is actually different.

We assigned these three groups

Okay, let’s take a look at our task driver first to elicit the knowledge points we want to learn.

Please show the maximum and average values ​​of different groups

Okay, let's show the code first and then explain it with the code.

SELECT AVG(sal),MAX(sal),deptno -- 这个就是按照我们的平均值 最大值 部门进行筛选的操作
FROM emp GROUP BY deptno; -- 按小组的形式进行查询 就是我们是按照小组进行查询的

Let’s look at the first sentence. The meaning behind this select statement is what data processing I want to display.

The second one is which table we query from, and the keyword group by is more important, that is, we originally had many people, but not all of them belong to the same group, so we grouped each group Display of average and maximum values ​​This is what the second sentence means

Small case 2

Okay let's look at another example

-- 显示每个部门的每种岗位的平均工资和最低工资 也即是说 我们每个部门的每个岗位的 一个部门的不同岗位里面的人数也是不同的 所以说 我们要进行新的统计处理 
SELECT AVG(sal),MAX(sal),deptno,job
FROM emp GROUP BY deptno,job;

This display shows the average salary and minimum salary for each position in each department. This is very similar to what we just saw, but in addition to multiple departments and one department,

Well, let’s think about it, each department is divided into ordinary employees, managers, and bosses, but the numbers represented are different. The number of ordinary employees is relatively high, and secondly, what we want to do is to say that each To match the average and maximum value of each position, you can group them under this group and assign them to the appropriate positions.

Insert image description here

In the picture above we can clearly see the grouping into departments.

Small case 3

Task--Display the departments whose average salary is less than 2,000


-- 分析 1.
SELECT AVG(sal) AS avg_sal ,deptno-- 我们采用别名的话 可以使我们的效率更加高效的处理 因为我们已经调用过一次我们的函数 我们如果不采取别名的话,我们
-- 我们肯定会再一次的调用
FROM emp GROUP BY deptno -- 这里规定我们计算的范围是哪里其实是 我们计算的范围是哪里
HAVING avg_sal < 2000;-- 
SELECT * FROM emp;

After the last two trainings, everyone must have mastered this, but with restrictions, our having was born. This is to check our group machines, and then there are restrictions, we can use having to solve it.

Summarize

Let’s analyze this code.

What follows select is what we want to display.

2.from tells us where the display performs data operations (tells us the grouping situation)

3.having is a restriction on queries

The matching of large values ​​is to group them under this group and assign them to the appropriate position.

[External link pictures are being transferred...(img-woUJp9aU-1643371820322)]

In the picture above we can clearly see the grouping into departments.

Small case 3

Task--Display the departments whose average salary is less than 2,000


-- 分析 1.
SELECT AVG(sal) AS avg_sal ,deptno-- 我们采用别名的话 可以使我们的效率更加高效的处理 因为我们已经调用过一次我们的函数 我们如果不采取别名的话,我们
-- 我们肯定会再一次的调用
FROM emp GROUP BY deptno -- 这里规定我们计算的范围是哪里其实是 我们计算的范围是哪里
HAVING avg_sal < 2000;-- 
SELECT * FROM emp;

After the last two trainings, everyone must have mastered this, but with restrictions, our having was born. This is to check our group machines, and then there are restrictions, we can use having to solve it.

Summarize

Let’s analyze this code.

What follows select is what we want to display.

2.from tells us where the display performs data operations (tells us the grouping situation)

3.having is a restriction on queries

Insert image description here

Guess you like

Origin blog.csdn.net/SpongeBob_shouse/article/details/122735981