mysql - order by frequency with multiple columns
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
精彩评论