mysql - 按多个列的频率排序

时间:2010-08-12 00:29:24

标签: sql mysql aggregate-functions

我有一个包含5列的表格:

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

如果我想按照这些标签的受欢迎程度(频率)显示排序结果,我会使用哪种查询?

1 个答案:

答案 0 :(得分:4)

由于表格未规范化,因此您必须先将其展平:

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

......在你可以数数之前:

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