MySQL COUNT() multiple columns

前端 未结 3 1063
囚心锁ツ
囚心锁ツ 2021-01-13 16:02

I\'m trying to fetch the most popular tags from all videos in my database (ignoring blank tags). I also need the \'flv\' for each tag. I have this working as I want if each

相关标签:
3条回答
  • 2021-01-13 16:14

    This is not exactly an answer to your question, but I believe that it is the best solution to your problem.

    Is it possible for you to change your schema? If so, I think it would be best if you normalized this by pulling the tags out into a separate table. In such a case, you might end up with 2 or 3 tables, depending on whether the tags can be arbitrary strings or are from a set/list. Under this set up, you'd have

    Videos (VideoId, Flv)
    Tags (TagId, TagName)
    VideoTags(TagId, VideoId)
    

    Then it becomes pretty easy to find the most popular tags.

    0 讨论(0)
  • 2021-01-13 16:22

    You need to unpivot the data:

    SELECT tag, COUNT(*)
    FROM (
        SELECT tag_1 AS tag
        UNION ALL
        SELECT tag_2 AS tag
        UNION ALL
        SELECT tag_3 AS tag
    ) AS X (tag)
    GROUP BY tag
    ORDER BY COUNT(*) DESC
    

    I'm not sure how the flv is determined for a particular tag, since each id can have a single flv and up to 3 tags, it seems like any tag can have many different flv.

    0 讨论(0)
  • 2021-01-13 16:36
    select tag, flv, count(*) as tag_count
    from (
      select tag_1 as tag, flv from videos
      UNION
      select tag_2 as tag, flv from videos
      UNION
      select tag_3 as tag, flv from videos
    ) AS X
    

    I think that will do it, although there will be double-counting if any record has the same values for two of the tags.

    UPDATE: added AS X.

    0 讨论(0)
提交回复
热议问题