在MySQL中逐行计数单词

时间:2019-05-23 21:36:50

标签: mysql sql function procedure

我需要构建一个查询以提取所合并的每一行的数量。 例子

餐桌产品 列说明

+----+---------------------------------------------+
| Id | Description                                 |
+----+---------------------------------------------+
| 1  | Love test Love by Love                      |
| 2  | Value of Value is Value of Value the Value  |
+----+---------------------------------------------+

结果可能是

+---+------+---------+
| 1 | Love | 3 times |
| 1 | test | 1 time  |
| 1 | by   | 1 time  |
+---+------+---------+

+---+-------+---------+
| 2 | Value | 5 times |
| 2 | of    | 2 times |
| 2 | is    | 1 times |
| 1 | the   | 1 times |
+---+-------+---------+

2 个答案:

答案 0 :(得分:1)

以下脚本将返回您想要的结果。来自Here

的代码
SELECT ID, concat(transcription,' ',COUNT(*),' Times')
FROM
(
    SELECT ID,SUBSTRING_INDEX( SUBSTRING_INDEX( Description, ' ', l10.n * 10 + l1.n + 1), ' ', -1) AS transcription
    FROM Product
    CROSS JOIN (
        SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 0
    ) l1
    CROSS JOIN (
        SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 0
    ) l10
    WHERE LENGTH(Description) - LENGTH( REPLACE( Description, ' ', '')) >= l10.n * 10 + l1.n
)A
GROUP BY ID, transcription;

答案 1 :(得分:0)

您需要在文本上运行COUNT

SELECT ID, COUNT(Description) AS Times
FROM TableName
GROUP BY ID