MySQL中内置了很多函数,本章节注主要介绍字符串函数。
常用的字符串函数如下:
演示样例:
1.concat
select concat('hello','dg');
2.lower
select lower('HELLO');
3. upper
select upper('hello');
4.lpad
select lpad('01',5,'-');
5.rpad
select rpad('01',5,'-');
6.trim
select trim(' hello dg ');
7.substring
select substring('hellodg',1,5);
为了方便实例演示,在此给出表结构和基础数据
表结构:
数据插入:
-- 插入数据
INSERT INTO emp (id, workno, name, gender, age, idcard, workaddress, entrydate) VALUES
('1', 'WN001', 'John', 'M', 28, '123456789012345678', 'Beijing', '2023-03-01'),
('2', 'WN002', 'Alice', 'F', 24, '123456789012345679', 'Shanghai', '2023-03-05'),
('3', 'WN003', 'Bob', 'M', 32, '123456789012345680', 'Guangzhou', '2023-03-08'),
('4', 'WN004', 'Cathy', 'F', 27, '123456789012345681', 'Shenzhen', '2023-03-11'),
('5', 'WN005', 'David', 'M', 30, '123456789012345682', 'Tianjin', '2023-03-15'),
('6', 'WN006', 'Emily', 'F', 26, '123456789012345683', 'Chongqing', '2023-03-18'),
('7', 'WN007', 'Frank', 'M', 33, '123456789012345684', 'Xian', '2023-03-22'),
('8', 'WN008', 'Grace', 'F', 29, '123456789012345685', 'Hangzhou', '2023-03-25'),
('9', 'WN009', 'Henry', 'M', 31, '123456789012345686', 'Nanjing', '2023-03-29'),
('10', 'WN010', 'Ivy', 'F', 25, '123456789012345687', 'Chengdu', '2023-04-02'),
('11', 'WN011', 'Jack', 'M', 29, '123456789012345688', 'Shenyang', '2023-04-06'),
('12', 'WN012', 'Kate', 'F', 27, '123456789012345689', 'Wuhan', '2023-04-09'),
('13', 'WN013', 'Leo', 'M', 33, '123456789012345690', 'Ningbo', '2023-04-13'),
('14', 'WN014', 'Maggie', 'F', 26, '123456789012345691', 'Changsha', '2023-04-16'),
('15', 'WN015', 'Nancy', 'F', 24, '123456789012345692', 'Harbin', '2023-04-20');
问题:由于业务变更,我们需要把企业员工id统一变为5位数。不足五位数的在前面补充0。如一号的id应该是00001。
代码如下:
update emp set id=lpad(id,5,'0');
这些字符串处理函数是最基本的内置函数,多应用就会慢慢掌握。