我有一张简单的表格:
id | fullname
---------------------------
1 | Ivanov Ivan Ivanovich
---------------------------
2 | Petrov Petr Petrovich
---------------------------
3 | Alym kyzy Ainura
我需要将它们变成这样的东西:
id | name_initials
--------------------
1 | Ivanov I. I.
--------------------
2 | Petrov P. P.
--------------------
3 | Alym k. A.
我可以通过PHP轻松实现,但MySQL是关于数据操作的。我认为,它可能(并且必须)仅使用DBMS完成。
如何通过纯SQL完成? 我应该为此编写存储函数,还是有更短的方法?
问候。
答案 0 :(得分:4)
你可以使用这样的查询:
SELECT
fullname,
CONCAT_WS(' ',
SUBSTRING_INDEX(fullname, ' ', 1),
CASE WHEN LENGTH(fullname)-LENGTH(REPLACE(fullname,' ',''))>2 THEN
CONCAT(LEFT(SUBSTRING_INDEX(fullname, ' ', -3), 1), '.')
END,
CASE WHEN LENGTH(fullname)-LENGTH(REPLACE(fullname,' ',''))>1 THEN
CONCAT(LEFT(SUBSTRING_INDEX(fullname, ' ', -2), 1), '.')
END,
CASE WHEN LENGTH(fullname)-LENGTH(REPLACE(fullname,' ',''))>0 THEN
CONCAT(LEFT(SUBSTRING_INDEX(fullname, ' ', -1), 1), '.')
END) shortname
FROM
Names
请参阅小提琴here。此查询最多支持四个名称。
答案 1 :(得分:1)
解决了存储功能:
CREATE FUNCTION `getNameInitials`(`fullname` VARCHAR(70))
RETURNS VARCHAR(70)
DETERMINISTIC
BEGIN
DECLARE `result` VARCHAR(70) DEFAULT '';
DECLARE `position` TINYINT;
DECLARE `separator` VARCHAR(1) DEFAULT ' ';
DECLARE `append` VARCHAR(1) DEFAULT '.';
DECLARE `buffer` VARCHAR(10);
SET `fullname` = CONCAT(TRIM(`fullname`), `separator`);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position`
THEN RETURN TRIM(`fullname`);
END IF;
SET `result` = LEFT(`fullname`, `position` - 1);
cycle: LOOP
SET `fullname` = SUBSTR(`fullname`, `position` + 1);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position` OR NOT LENGTH(`fullname`)
THEN LEAVE cycle;
END IF;
SET `buffer` = CONCAT(LEFT(`fullname`, 1), `append`);
SET `result` = CONCAT_WS(`separator`, `result`, `buffer`);
END LOOP cycle;
RETURN `result`;
END
选中:
SELECT
getNameInitials(`fullname`) as `name`
FROM
(
SELECT
'Ivanov Ivan Ivanovich' as `fullname`
UNION ALL
SELECT 'Alym kyzy Ainura'
) `sub`;
得到以下结果:
'Ivanov I. I.'
'Alym k. A.'
答案 2 :(得分:0)
CREATE DEFINER=`root`@`localhost` FUNCTION `getNameInitials`(`fullname` VARCHAR(500), `separator` VARCHAR(1)) RETURNS varchar(70) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE `result` VARCHAR(500) DEFAULT '';
DECLARE `position` TINYINT;
SET `fullname` = TRIM(`fullname`);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position`
THEN RETURN LEFT(`fullname`,1);
END IF;
SET `fullname` = CONCAT(`fullname`,`separator`);
SET `result` = LEFT(`fullname`, 1);
cycle: LOOP
SET `fullname` = SUBSTR(`fullname`, `position` + 1);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position` OR NOT LENGTH(`fullname`)
THEN LEAVE cycle;
END IF;
SET `result` = CONCAT(`result`,LEFT(`fullname`, 1));
-- SET `result` = CONCAT_WS(`separator`, `result`, `buffer`);
END LOOP cycle;
RETURN upper(`result`);
END
1.在mysql中执行此功能。 2.这将创建一个功能。现在,您可以在任何地方使用此功能。
SELECT `getNameInitials`('Kaleem Ul Hassan', ' ') AS `NameInitials`;