使用MySQL获取整数的零数

时间:2017-02-02 11:40:51

标签: mysql

假设我在MySQL(10090)中有一个整数值。我需要计算该数字中所有出现的零位数。因此对于前一种情况,它将返回3:

select count_zeros(number) from dual;
-- when number = 10090, it return 3
-- when number = 10000, it return 4

如何使用MySQL查询以最快的方式实现这一目标?

2 个答案:

答案 0 :(得分:6)

您可以使用以下解决方案,比较字符串长度是否包含您想要计算的字符(在您的情况下为0) - 使用LENGTH的解决方案:

SELECT 
   (LENGTH(number) - LENGTH(REPLACE(number, '0', ''))) AS zero_count
FROM dual;
-- 10090: 3
-- 10000: 4
  

演示: http://sqlfiddle.com/#!9/4262b6/3/0

在字符串上计算多字节字符(如§)的更好解决方案,您可以使用CHAR_LENGTH使用以下解决方案:

SELECT 
    (CHAR_LENGTH(number) - CHAR_LENGTH(REPLACE(number, '0', ''))) AS zero_count
FROM dual;
-- 10090: 3
-- 10000: 4
  

演示(使用字符串示例): http://sqlfiddle.com/#!9/b11ee2/2/1

在MySQL上,你也可以create a function以更简单的方式使用它:

CREATE FUNCTION getCharCount (colValue VARCHAR(255), searchValue CHAR(1)) 
RETURNS INT DETERMINISTIC
RETURN (CHAR_LENGTH(colValue) - CHAR_LENGTH(REPLACE(colValue, searchValue, '')));

通过使用此功能(getCharCount),您可以使用以下查询:

SELECT number, getCharCount(number, '0') AS charCount FROM dual;
-- 10090: 3
-- 10000: 4
  

演示: http://sqlfiddle.com/#!9/a550e9/1/0

答案 1 :(得分:0)

我认为首先要做的是将这些整数值转换为字符串。

https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_cast

然后查找某个字符的出现

https://lists.mysql.com/mysql/215049

mysql> create table numbers(x int);
Query OK, 0 rows affected (0,38 sec)
mysql> select * from numbers;
+-----------+
| x         |
+-----------+
|    123000 |
|      1300 |
|    135600 |
| 135623400 |
|     13560 |
|    135160 |
|  13514560 |
|   1351120 |
|  13512310 |
+-----------+
9 rows in set (0,00 sec)

查找零的出现

mysql> select x, round((length(cast(x as char(11))) - length( replace( cast( x as char(11) ), "0", "" ) ))/length("0")) as str_x from numbers limit 5;
+-----------+-------+
| x         | str_x |
+-----------+-------+
|    123000 |     3 |
|      1300 |     2 |
|    135600 |     2 |
| 135623400 |     2 |
|     13560 |     1 |
+-----------+-------+
5 rows in set (0,00 sec)

找到thirteens

mysql> select x, round((length(cast(x as char(11))) - length( replace( cast( x as char(11) ), "13", "" ) ))/length("13")) as str_x from numbers;
+-----------+-------+
| x         | str_x |
+-----------+-------+
|    123000 |     0 |
|      1300 |     1 |
|    135600 |     1 |
| 135623400 |     1 |
|     13560 |     1 |
|    135160 |     1 |
|  13514560 |     1 |
|   1351120 |     1 |
|  13512310 |     1 |
| 132134534 |     2 |
+-----------+-------+
10 rows in set (0,00 sec)

mysql>