开发者

mysql - order by frequency with multiple columns

开发者 https://www.devze.com 2023-01-11 09:34 出处:网络
I have a table with 5 columns: tag 1 tag 2 tag 3 tag 4 tag 5 If I want to show result开发者_StackOverflow中文版s ordered by the popularity(frequency) of those tags, what kind of query would i use?

I have a table with 5 columns:

  • tag 1
  • tag 2
  • tag 3
  • tag 4
  • tag 5

If I want to show result开发者_StackOverflow中文版s ordered by the popularity(frequency) of those tags, what kind of query would i use?


Because the table isn't normalized, you'll have to flatten it first:

SELECT a.column, a.tag1 AS tag
  FROM TABLE a
UNION ALL
SELECT b.column, b.tag2
  FROM TABLE b
UNION ALL
SELECT c.column, c.tag3
  FROM TABLE c      
UNION ALL
SELECT d.column, d.tag4
  FROM TABLE d
UNION ALL
SELECT e.column, e.tag5
  FROM TABLE e

...before you can count them:

SELECT t.tag, COUNT(*) tag_popularity
  FROM (SELECT a.column, a.tag1 AS tag
          FROM TABLE a
        UNION ALL
        SELECT b.column, b.tag2
          FROM TABLE b
        UNION ALL
        SELECT c.column, c.tag3
          FROM TABLE c      
        UNION ALL
        SELECT d.column, d.tag4
          FROM TABLE d
        UNION ALL
        SELECT e.column, e.tag5
          FROM TABLE e) x
GROUP BY x.tag
ORDER BY tag_popularity DESC
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号