虽然性能会很糟糕,但此存储过程将为您提供您要求的结果:
CREATE PROCEDURE ex12688666(whatever TEXT)
DETERMINISTIC
READS SQL DATA
SQL SECURITY INVOKER
COMMENT ''
proc: BEGIN
DECLARE not_found BOOL DEFAULT FALSE;
DECLARE max BIGINT UNSIGNED DEFAULT 0;
DECLARE len BIGINT UNSIGNED;
DECLARE i BIGINT UNSIGNED;
DECLARE pos BIGINT UNSIGNED;
DECLARE result LONGBLOB DEFAULT '';
DECLARE cur1 CURSOR FOR
SELECT id FROM ids WHERE id RLIKE whatever ORDER BY id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = TRUE;
SELECT MAX(id) INTO max FROM ids;
IF (max > 0) THEN
SET len = FLOOR((max + 7) / 8);
SET result = REPEAT("\0", len);
OPEN cur1;
loop1: LOOP
FETCH cur1 INTO i;
IF not_found THEN
LEAVE loop1;
END IF;
SET pos = FLOOR(i / 8) + 1;
SET result = CONCAT(
SUBSTRING(result, 1, pos - 1),
CHAR(ASCII(SUBSTRING(result, pos, 1)) | (1 << (i MOD 8))),
SUBSTRING(result, pos + 1)
);
END LOOP;
CLOSE cur1;
END IF;
SELECT HEX(result) AS result;
END;
我们返回HEX(result)
是为了说明目的。在实践中,可以替换
SELECT HEX(result) AS result;
简单地
SELECT result;
或者如果你想对结果进行 zlib 压缩:
SELECT COMPRESS(result) AS result;
这应该得到你提到的额外荣誉。
有关交互式演示,请参见http://sqlfiddle.com/#!2/6f5c0/1 。