mysql - MySQL 中可以进行值排序吗?

标签 mysql

示例:

如果我有一个名为 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

fiddle

它工作起来很慢,为了加快进程我建议你创建新列 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/

相关文章:

php - 使用 CodeIgniter 的 MySQL 查询问题

mysql - MySQL 条件左连接

mysql - fatal error : Call to a member function num_rows() on boolean in C:\xamp\htdocs\project24\system\database\DB_driver. php 第 768 行

c# - 测试条件如何基于查询结果的计数?

mysql - 在 SQLAlchemy 中,如何指定全文索引?

php - 刷新php时双重提交

php - 从 sql 结果在 PHP 中为 json 创建一个关联数组

php - Facebook 在哪里存储数百万个图像和视频。在数据库或其他地方?如果是这样,在哪里?

python - 在 flask 模板中访问这些字典值

php - MySQL - PDO - 如果 POSTS 为 NULL,则允许