示例:
如果我有一个名为 products
的数据库表和一个名为 product_title
的列
product_title
下的内容
zyx
cba
defabc
我需要什么?
`zyx` should be changed `xyz`
`cba` should be changed `abc`
`defabc` should be changed `abcdef`
所有值按字母顺序排列。
我尝试了什么?
我尝试搜索需求,但找不到任何解决方案。我只想知道“这可能吗”?
如果这不可能,我如何用最匹配的子字符串对我的记录进行排序?
最佳答案
mysql 中没有内置函数对字符串中的符号进行排序。
无论如何您都可以创建自己的存储过程:
CREATE FUNCTION sv(
x VARCHAR(255)
)
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
declare r varchar(255);
declare maxlen int;
declare pos int;
declare sym char(1);
declare npos int;
set r = "";
set maxlen = length(x);
set pos = 1;
while (pos <= maxlen) do
set sym = substr(x, pos, 1);
set npos = 1;
while ((npos <= length(r)) and (substr(r, npos, 1) < sym)) do
set npos = npos + 1;
end while;
set r = concat(substr(r, 1, npos-1), sym, substr(r, npos));
set pos = pos + 1;
END while;
return r;
END
它工作起来很慢,为了加快进程我建议你创建新列 product_title_sorted
,运行 update products set product_title_sorted=sv(product_title) where product_title_sorted is null
然后在您的查询中使用 product_title_sorted
关于mysql - MySQL 中可以进行值排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804649/