【问题标题】:Complex Mysql query复杂的Mysql查询
【发布时间】:2010-11-11 12:51:55
【问题描述】:

我在 mysql 中的验证中从 group_concat() 得到低于值

abc#123#def#456#xyz#789#10111#

现在我想运行查询/存储过程,它可以在列中打破这个字符串

abc | 123 |定义 |第456章xyz |第789章10111 |

【问题讨论】:

  • dun需要这么麻烦,当你group_concat不使用#作为分隔符时,将其更改为|或将查询/过程更改为分隔符的接受变量

标签: mysql


【解决方案1】:

如果这是我真正想要的,我会更改查询以返回列名。让 MySQL 将字符串放在一起,然后在中间层将它们分开,这似乎是一种 CPU 浪费。

有两个查询:一个返回连接的值,另一个只返回原始值:“abc”、“123”、“def”等。

【讨论】:

  • 第一个查询是从不同的行获取一组类似用户的值。必须使用查询在列中更改它们
  • 仍然没有意义 - 实际上现在更少了。
【解决方案2】:

试试这个:

drop procedure if exists foo;

delimiter #

create procedure foo
(
in p_csv varchar(1024)
)
proc_main:begin

declare v_token varchar(255);
declare v_done tinyint unsigned default 0;
declare v_token_idx int unsigned default 1;

    if p_csv is null or length(p_csv) <= 0 then
        leave proc_main;
    end if;

    -- split the string into tokens and put into an in-memory table...

    create temporary table tokens(
        token_id smallint unsigned auto_increment primary key, 
        token varchar(255)
    )engine = memory;   

    while not v_done do
    set v_token = trim(substring(p_csv, v_token_idx, 
      if(locate('#', p_csv, v_token_idx) > 0, 
                locate('#', p_csv, v_token_idx) - v_token_idx, length(p_csv))));

      if length(v_token) > 0 then
        set v_token_idx = v_token_idx + length(v_token) + 1;
                insert into tokens (token) values(v_token);
      else
        set v_done = 1;
      end if;
    end while;

    select * from tokens order by token_id;

    drop temporary table if exists tokens;

end proc_main #

delimiter ;

call foo('abc#123#def#456#xyz#789#10111#');

【讨论】:

  • 谢谢。但我希望输出单行(7 列)而不是 7 行
  • 那要我帮你做吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
相关资源
最近更新 更多