当一个字段包含多个值时,Mysql计数和分组

时间:2014-09-30 07:38:06

标签: mysql

让我们有类似的事情:

mysql> SELECT field1, field2 FROM mytable;
+--------+-------------+
| field1 | field2      |
+--------+-------------+
| tom    | a,b,c       |
| jerry  | a,c         |
| mick   | b           |
| steve  | a           |
+--------+-------------+

我希望得到字段2中单个值的计数,即:

+--------+-------------+
| value  | count       |
+--------+-------------+
| a      | 3           |
| b      | 2           |
| c      | 2           |
+--------+-------------+

1 个答案:

答案 0 :(得分:0)

Tyr this:

DELIMITER $$
DROP PROCEDURE IF EXISTS `proc_split`$$
CREATE PROCEDURE `proc_split`(
    inputstring VARCHAR(1000),
    delim CHAR(1)
)
BEGIN
    DECLARE strlen INT;
    DECLARE last_index INT;
    DECLARE cur_index INT;
    DECLARE cur_char VARCHAR(200);
    DECLARE len INT;
    SET cur_index=1;
    SET last_index=0;
    SET strlen=LENGTH(inputstring);  
    DROP TABLE IF EXISTS splittable;
    CREATE TEMPORARY TABLE splittable(
        id INT AUTO_INCREMENT,
        v VARCHAR(20),
        PRIMARY KEY (`ID`),
        UNIQUE KEY `ID` (`ID`)
    ) ;
    WHILE(cur_index<=strlen) DO    
    BEGIN
        IF SUBSTRING(inputstring FROM cur_index FOR 1)=delim OR cur_index=strlen THEN
            SET len=cur_index-last_index-1;
            IF cur_index=strlen THEN
               SET len=len+1;
            END IF;
            INSERT INTO splittable(`v`) VALUES (SUBSTRING(inputstring FROM   (last_index+1) FOR len));
            SET last_index=cur_index;
        END IF;
        SET cur_index=cur_index+1;
    END;
    END WHILE;
END$$
DELIMITER ;

调用程序存储结果到临时表,然后得到你需要的

CALL proc_split((select group_concat(field2) from mytable),',');

SELECT *,count(1) as count FROM splittable group by v;

group_concat有字符串限制,如果表中有太多记录,则应在mysql配置中配置此值