MySQL查询选择字段中的第一个单词并返回计数

时间:2017-08-07 22:02:04

标签: mysql sql

我需要一个MySQL查询,只计算字符串第一个单词的出现次数,然后按计数递减排序。

这是我的尝试,但不起作用:

   SELECT COUNT(SUBSTRING_INDEX(`logotitle`, ' ', 1)) as var
   FROM tbllogos
   ORDER BY var DESC

示例:

四个数据库条目:

  1. 水果标志

  2. Apple徽标

  3. Apple Fruit Logo

  4. 香蕉标志

  5. 查询应返回:

    Apple 2

    香蕉1

    水果1

3 个答案:

答案 0 :(得分:2)

我认为你在寻找:

SELECT SUBSTRING_INDEX(`logotitle`, ' ', 1) as var, COUNT(*) as cnt
FROM tbllogos
GROUP BY var
ORDER BY cnt DESC

答案 1 :(得分:2)

试试这个:

SELECT SUBSTRING_INDEX(logotitle, ' ',1) AS var, COUNT(*) FROM tbllogos GROUP BY var;

结果:

+--------+----------+
| var    | COUNT(*) |
+--------+----------+
| Apple  |        2 |
| Banana |        1 |
| Fruit  |        1 |
+--------+----------+

答案 2 :(得分:0)

SELECT SUBSTRING(logotitle, 1, INSTR(logotitle, ' ')) AS var, COUNT(*) AS count
FROM tbllogos
GROUP BY var
ORDER BY count DESC