写程序来完成所有字母

时间:2014-09-22 23:10:34

标签: mysql sql stored-procedures

我需要编写一个运行相同命令但需要更改LIKE字段的过程。它将从'aa%'开始,然后一直到'ab%'到'az%'。那么它将以'ba%','bb%'开始,依此类推,直到'zz%'。我尝试在循环中运行它,但不知道从哪里获取字母。

SELECT t1.colA, t2.colA, count(*)
FROM (SELECT colA FROM table WHERE colA LIKE "a[a-z]%") t1
JOIN table t2
ON t1.date = t2.date
GROUP BY t1.colA, t2.colA
HAVING count(*) > 10
INSERT INTO /tmp/[a[a-z]].csv
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'

经过26次迭代后,下一次将是

 SELECT t1.colA, t2.colA, count(*)
    FROM (SELECT colA FROM table WHERE colA LIKE "b[a-z]%") t1
    JOIN table t2
    ON t1.date = t2.date
    GROUP BY t1.colA, t2.colA
    HAVING count(*) > 10
    INSERT INTO /tmp/[b[a-z]].csv
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    LINES TERMINATED BY '\r\n'

接下来将是

SELECT t1.colA, t2.colA, count(*)
FROM (SELECT colA FROM table WHERE colA LIKE "c[a-z]%") t1
JOIN table t2
ON t1.date = t2.date
GROUP BY t1.colA, t2.colA
HAVING count(*) > 10
INSERT INTO /tmp/[c[a-z]].csv
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'

等等,直到

SELECT t1.colA, t2.colA, count(*)
FROM (SELECT colA FROM table WHERE colA LIKE "z[a-z]%") t1
JOIN table t2
ON t1.date = t2.date
GROUP BY t1.colA, t2.colA
HAVING count(*) > 10
INSERT INTO /tmp/[z[a-z]].csv
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'

1 个答案:

答案 0 :(得分:1)

一种选择是使用REPEAT。字符的ASCII码值' a'通过' z'在97到122之间,我们可以使用CHAR()函数返回给定ASCII代码值的字符。

例如:

BEGIN
    DECLARE c VARCHAR(1);
    DECLARE i INT;
    SET i = 97;
    REPEAT
        SET c = CHAR(i);

        -- SELECT c;

        SET i = i + 1;
    UNTIL i > 122 END REPEAT;
END