dongyi6183 2014-05-18 09:11
浏览 34
已采纳

获得最常用的标签

Hello guys i am trying to get the most used tags from the database as show below:

+------------------------+
| post |       tags      |
+------------------------+
|  1   | ["php", "sql"]  |
|  2   | ["php", "html"] |
|  3   | ["css", "html"] |
|  4   |["php", "html5"] |
|  5   | ["php", "css"]  |
+------------------------+

I want to get the n most used tags in this table I hoping you guys can help me set up a SQL Query, i cant find myself a way to start, thanks!

  • 写回答

1条回答 默认 最新

  • douwen8424 2014-05-18 09:37
    关注

    You should probably consider re-designing your database to something like this:

    Table: Posts
    +=======================================================+
    id    |    title    |    body    | user_id    |    etc..
    +-------------------------------------------------------+
    
    Table: Tags
    +=====================+
    id    |    name   
    +---------------------+
    
    Table: Post_tags
    +======================+
    post_id    |    tag_id
    +----------------------+
    

    Suppose you insert a new post with tags [php] and [html]. Then you will add the post to the Posts table, and add two rows to the Post_tags table, based on values stored in the Tags table:

    Table: Posts
    +========================================================+
    id    |    title    |    body    | user_id    |    etc..
    +-------------------------------------------------------+
    1     |  New Post!  | Post body! |   2564     |    ...
    
    Table: Tags
    +======================+
    id    |    name   
    +----------------------+
      1   |    html
      2   |     php
    
    Table: Post_tags
    +======================+
    post_id    |    tag_id
    +----------------------+
     1         |   1
     1         |   2
    

    Now, to get the most popular tags, you would just do something like this:

    SELECT 
        tag_id,
        COUNT(tag_id)
    FROM Post_tags
    GROUP BY tag_id
    

    which will give you a list of each tag and the number of times it has been used in a post.

    Sorry, I know this doesn't exactly answer your question. If you really need to store the JSON style string of tags, you could do that as well in Posts, but to use that to get tag statistics is probably going to add far more complexity than necessary, and separating your data into relational tables is a much more effective way of doing things. Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100