Count number of unique characters in a string

后端 未结 6 1178
挽巷
挽巷 2020-12-11 03:41

I\'m looking for a sql statement to count the number of unique characters in a string.

e.g.

3333333333 -> returns 1
1113333333 -> returns 2
111         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 04:27

    One thing you can do is have a table of all your characters, such as:

    mysql> select * from chars;
    +----+------+
    | id | c    |
    +----+------+
    |  1 | 1    |
    |  2 | 2    |
    |  3 | 3    |
    |  4 | 4    |
    +----+------+
    

    If your table of words looks like this:

    mysql> select * from words;
    +----+-----------+
    | id | word      |
    +----+-----------+
    |  1 | 111222333 |
    |  2 | 11111111  |
    |  3 | 2222111   |
    |  4 | 5555555   |
    +----+-----------+
    

    You can then join these tables on the condition of the character being in the word, and get the count, like this:

    mysql> select word, count(c) from words w inner join chars c on locate(c.c, word) group by word;
    +-----------+----------+
    | word      | count(c) |
    +-----------+----------+
    | 11111111  |        1 |
    | 111222333 |        3 |
    | 2222111   |        2 |
    +-----------+----------+
    

提交回复
热议问题