Zero-based self-study SQL course | Complete collection of SQL basic functions

Hello everyone, my name is Ning Yi.

Today is our 20th lesson: SQL basic functions.

There are many built-in functions in MySQL, which are used to process numbers, strings, dates, etc. In this lesson, we will talk about the commonly used functions.

1. Numerical functions

-- ROUND(数值,保留小数)  四舍五入
SELECT ROUND(3.456, 2);  -- 3.46
-- TRUNCATE(数值,保留小数)  截断
SELECT TRUNCATE(3.456, 2);  -- 3.45
-- CEILING(数值)  大于等于此数的最小整数
SELECT CEILING(3.456);  -- 4
-- FLOOR(数值)  小于等于此数的最大整数
SELECT FLOOR(3.456);  -- 3
-- ABS(数值)  绝对值
SELECT ABS(-3.456);  -- 3.456
-- RAND()  随机函数,0到1的随机值
SELECT RAND();  -- 0.9206498273840639

2. String functions

-- LENGTH(字符串)   字符串长度
SELECT LENGTH('Cat');  -- 3
-- UPPER(字符串)   转大写
SELECT UPPER('Cat');  -- 'CAT'
-- LOWER(字符串)   转小写
SELECT LOWER('Cat');  -- 'cat'
-- TRIM(字符串)   去掉两边空格
SELECT TRIM('  Cat  '); -- 'Cat'
-- LTRIM(字符串)   去掉左边空格
SELECT LTRIM('  Cat  '); -- 'Cat  '
-- RTRIM(字符串)    去掉右边空格
SELECT RTRIM('  Cat  '); -- '  Cat'
-- LEFT(字符串,字符长度n)   从左边开始取n个字符
SELECT LEFT('CatNing', 4); -- 'CatN'
-- RIGHT(字符串,字符长度n)   从右边开始取n个字符
SELECT RIGHT('CatNing', 4); -- 'Ning'
-- SUBSTRING(字符串,开始位置s,字符长度n)   从第s个字符开始计算,取n个字符
-- 这里要注意与其他编程语言分开,其他编程语言索引大多从0开始,而在SQL中是从1开始
SELECT SUBSTRING('CatNing', 3, 4); -- 'tNin'
-- LOCATE(字符a,字符b)   定位字符a在字符b中首次出现的位置,没有的话则返回0
-- 不区分大小写
SELECT LOCATE('ning', 'CatNing');  -- 4
-- REPLACE(字符a,字符b,字符c)   在字符a中,用字符串c替换字符串b
-- 区分大小写
SELECT REPLACE('CatNing', 'Cat', 'Mao'); -- 'MaoNing'
-- CONCAT(字符a,字符b)   将字符a、字符b拼接起来
SELECT CONCAT('Cat', 'Ning'); -- 'CatNing'

Homework: Concatenate the student name Sname and the student gender Ssex in the Students table, add a space in the middle, and add a column of random numbers.

Example results:

SELECT
  CONCAT(Sname,' ',Ssex) AS "姓名 性别",
  RAND() AS '随机数'
FROM Students;

In the next lesson we will talk about MySQL date functions.

Click to follow and update the course as soon as possible~

 

Guess you like

Origin blog.csdn.net/shine_a/article/details/125448526