我有一个包含5列的表格:
如果我想按照这些标签的受欢迎程度(频率)显示排序结果,我会使用哪种查询?
答案 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