通常存在这样的情况: Web表单输入产生几个相同长度的数组,其中每个数组是需要包含在查询的特定部分中的不同变量。假设你有......
set @transforms = "a,b,c"; set @bys = "colX,colY,colZ";
......你想要......
+------+---+------+
| row | x | x |
+------+---+------+
| 1 | a | colX |
| 2 | b | colY |
| 3 | c | colZ |
+------+---+------+
这样做是否有最佳做法,或至少是此类问题的名称?据我所知,它可能已经是ArtfulSoftware上的一个例子,我只是不知道要寻找什么标题。我能想出的最好的是下面的代码,但感觉我正在重新发明轮子,而我宁愿以任何方式做到这一点,那些人真正知道他们在做什么。有什么建议?感谢。
DELIMITER ##
DROP PROCEDURE IF EXISTS twoarrays ##
CREATE PROCEDURE hs.twoarrays
-- example usage:
-- call twoarrays('array1','array2','delim1','delim2')
(
IN array1 VARCHAR(2000),
IN array2 VARCHAR(2000),
IN delim1 VARCHAR(10),
IN delim2 VARCHAR(10)
)
BEGIN
IF delim1 is NULL THEN SET delim1 = ','; END IF;
IF delim2 is NULL THEN SET delim2 = delim1; END IF;
set @@group_concat_max_len = 99999;
select @foo := concat("select @rowa := @rowa + 1 as row, '",
replace(array1,delim1,"' x union select @rowa := @rowa + 1,'"),
"' from (select @rowa := 0) r");
select @bar := concat("select @rowb := @rowb + 1 as row, '",
replace(array2,delim2,"' x union select @rowb := @rowb + 1,'"),
"' from (select @rowb := 0) r");
select @baz := concat("select a.*,b.x from (",
@foo,
") a join (",
@bar,
") b on a.row = b.row");
prepare twoarrayproc from @baz;
execute twoarrayproc;
END ##
DELIMITER ;
call twoarrays(@transforms,@bys,NULL,NULL);