有趣的问题。下面有很多,所以让我们分解一下。我们本质上是构建一个查询并执行 stmt
DELIMITER $$
DROP PROCEDURE IF EXISTS proc_loop_test$$
CREATE PROCEDURE proc_loop_test()
#create empty query string
set @sqlstring = '';
#set your string of fields, not sure where this comes from
set @mystring = 'field1=lance,field2=peter,field3=john';
#create number of times we will loop through the string
set @num = (select length(@mystring)
- length(replace('field1=lance,field2=peter,field3=john',',','')) +1);
#init loop
loop LOOP
#create a short string just taking the "last" field/value pair
set @shtstring = (select SUBSTRING_INDEX(@mystring,',',-1));
#recreate your query string removing the substring we created
set @mystring = (select left(replace(@mystring,@shtstring,''),length(replace(@mystring,@shtstring,''))-1));
#add to your query string, we will build this for each
set @sqlstring = concat(@sqlstring ,(select
concat('''',SUBSTRING_INDEX(@shtstring,'=',-1),''''
,' as ',
left(@shtstring,(position('=' in @shtstring) -1))) ),',');
#reduce our count by one as we have removed the latest field
set @num = @num - 1;
#leave the loop when no fields left
if @num = 0 then leave LOOP;
end if;
end loop LOOP;
END$$
DELIMITER ;
#create a query statement to execute
set @query = (select concat('select ',left(@sqlstring, length(@sqlstring)-1)));
#execute the query!
PREPARE stmt FROM @query;
EXECUTE stmt;
结果
field3 field2 field1
john peter lance
没有数组逻辑,这在 presto SQL 等中会很简单。因为您可以随时定义任意数量的字段,我们将需要loop,不幸的是您不能循环进入mysql无需创建procedure
这是前几行。我们还根据您的源和迭代次数(字符串中的字段数)创建完整的字符串。
然后基本上我们迭代地隔离“最后一个”字段/值对,重新排列每一个,以便field1=john 变成更适合 sql 的 'john' as field',
每次循环时我们都会减少计数器和字符串,直到计数器为 0。此时我们停止。
然后我们 prepare 使用我们的值/字段对和“选择”字符串进行查询。然后execute 你得到你的值作为字段
信用
Dynamic Strings prepare/exec
Looping and stored procs
Simulating Split function