我想获得存储在字段myfield
(varchar(128))中的所有字符串大小及其出现次数(即具有该特定长度的行数)。这就是我到目前为止所做的:
MySQL > SELECT SUM(CHAR_LENGTH(myfield)=5) as occurr from mytable;
+--------+
| occurr |
+--------+
| 9194 |
+--------+
1 row in set (0.39 sec)
MySQL > SELECT SUM(CHAR_LENGTH(myfield)=6) as occurr from mytable;
+--------+
| occurr |
+--------+
| 11636 |
+--------+
1 row in set (0.44 sec)
MySQL > SELECT SUM(CHAR_LENGTH(myfield)=7) as occurr from mytable;
+--------+
| occurr |
+--------+
| 19022 |
+--------+
1 row in set (0.48 sec)
有没有办法用一个SQL命令获取这些数据?像这样的输出:
+--------+--------+
| length | occurr |
+--------+--------+
| 5 | 9194 |
+--------+--------+
| 6 | 11636 |
+--------+--------+
| 7 | 19022 |
+--------+--------+
答案 0 :(得分:2)
您可以简单地使用:
SELECT CHAR_LENGTH(myfield) AS length, COUNT(*) AS occurr
FROM mytable
WHERE CHAR_LENGTH(myfield) IN (5,6,7)
GROUP BY CHAR_LENGTH(myfield)
如果您对某些特定字符长度不感兴趣,您当然可以删除WHERE
子句。
答案 1 :(得分:1)
SELECT CHAR_LENGTH(my_field) AS
长度为, COUNT(*) AS
{occurr {1}} {mytable的{1}}
我还在打字,因为另一个答案出现了。基本相同 - 除了包含CHAR_LENGTH()没有限制。
答案 2 :(得分:1)
SELECT CHAR_LENGTH(myfield) as length, COUNT(*) as occurence FROM mytable WHERE CHAR_LENGTH(myfield) BETWEEN 4 and 6 GROUP BY length
编辑:我或多或少地同时发布了相同的答案。我当然不打算偷一个答案。