【问题标题】:Is Value sorting possible in MySQL?MySQL中是否可以进行值排序?
【发布时间】:2016-03-04 19:36:16
【问题描述】:

示例:

如果我有一个名为 products 的数据库表和一个名为 product_title 的列

product_title下的内容

zyx
cba
defabc

我需要什么?

`zyx` should be changed `xyz`
`cba` should be changed `abc`
`defabc` should be changed `abcdef`

所有值按字母顺序排列。

我尝试了什么?

我尝试搜索需求,但找不到任何解决方案。我只想知道“这可能吗”

如果这是不可能的,我如何使用最匹配的子字符串对我的记录进行排序?

【问题讨论】:

  • 不确定我是否理解。你想update数据--update table set field = 'xyz' where field = 'zyx'吗?
  • 不完全是@sgeddes,我们不能暂时强制转换字段以按字母顺序排序吗?
  • 我相信 OP 是在询问 MySQL 是否能够在选择后按字母顺序对值字符串进行排序。 @ameenulla0007 请确认这是您想要的。
  • 为什么需要按字母顺序对列的内容进行排序?您不会在一列中存储多个数据,对吗?

标签: mysql


【解决方案1】:

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

【讨论】:

  • 这很好,但我想知道,这是面向性能的吗?
  • 不,这是缓慢的方法
  • 哦!但感谢@lashane 的回复和帮助。谢谢你.. :)
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 2011-03-25
  • 2018-04-20
相关资源
最近更新 更多