如何对mysql表中的列中的单词进行计数和排序[关闭]

问题描述 投票:0回答:1

我的单词表列如下

stt_id | stt_hashtag           |stt_country |stt_time|
1      |ClimateAction CleanSeas|in          |1582466615
2      |LetsCrackIt ContestAle |in          |1582466741
       | Crackathon ...        |            |
3      |LetsCrackIt            |in          |1582467875
4      |LetsCrackIt            |in          |1582467883

我尝试了这个查询,但是没有用

SELECT COUNT(*), stt_hashtag 
FROM `st_trend_states` 
WHERE `country` = 'in' 
GROUP BY stt_hashtag

我想按出现的最高顺序来计算单词和顺序

mysql group-by sql-order-by aggregate-functions
1个回答
0
投票

您可以通过这样的查询来做到这一点:

SELECT  count(*) as wordcount,
        SUBSTRING_INDEX(SUBSTRING_INDEX(stt_hashtag, ' ', wordnr), ' ', -1) as singleword
FROM `st_trend_states` 
CROSS JOIN ( SELECT 1 as wordnr UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5) as wc
WHERE
    `stt_country` = 'in' 
AND
    wordnr <= CHAR_LENGTH(stt_hashtag) - CHAR_LENGTH(REPLACE(stt_hashtag,' ','')) +1
GROUP BY singleword
ORDER BY wordcount DESC, singleword ASC;

样本

mysql> SELECT * FROM st_trend_states;
+----+---------------------------------------+-------------+------------+
| id | stt_hashtag                           | stt_country | stt_time   |
+----+---------------------------------------+-------------+------------+
|  1 | ClimateAction CleanSeas               | in          | 1582466615 |
|  2 | LetsCrackIt ContestAle Crackathon ... | in          | 1582466741 |
|  3 | LetsCrackIt                           | in          | 1582467875 |
|  4 | LetsCrackIt                           | in          | 1582467875 |
+----+---------------------------------------+-------------+------------+
4 rows in set (0.00 sec)

mysql> 

查询

mysql> SELECT  count(*) as wordcount,
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(stt_hashtag, ' ', wordnr), ' ', -1) as singleword
    -> FROM `st_trend_states` 
    -> CROSS JOIN ( SELECT 1 as wordnr UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5) as wc
    -> WHERE
    -> `stt_country` = 'in' 
    -> AND
    -> wordnr <= CHAR_LENGTH(stt_hashtag) - CHAR_LENGTH(REPLACE(stt_hashtag,' ','')) +1
    -> GROUP BY singleword
    -> ORDER BY wordcount DESC, singleword ASC;
+-----------+---------------+
| wordcount | singleword    |
+-----------+---------------+
|         3 | LetsCrackIt   |
|         1 | ...           |
|         1 | CleanSeas     |
|         1 | ClimateAction |
|         1 | ContestAle    |
|         1 | Crackathon    |
+-----------+---------------+
6 rows in set (0.00 sec)

mysql> 
© www.soinside.com 2019 - 2024. All rights reserved.