选择具有最高出现次数的单词

时间:2015-02-04 10:18:04

标签: php mysql sql select

我有下表:

id  tag1     tag2    tag3
1   apple  orange   pears
2   orange  apple   pears
3   pears  orange   apple
4   orange  apple   pears
5   apple  orange   orange

我想得到这个

tag      count
orange    6
apple     5
pears     4

我无法使我的查询有效

$res = mysql_query("SELECT tag, count(tag) occurrences
FROM
(
  SELECT col, tag
  FROM $tbl_name
  unpivot
  (
    tag
    for col in (tag1, tag2, tag3)
  ) unpiv
) d
GROUP BY tag 
order by occurrences desc");

它基本上没有输出......某处出现错误。

2 个答案:

答案 0 :(得分:0)

MySQL中没有枢轴或无法转换功能。但是,您可以使用联合,类似于此处所做的:MySQL - turn table into different table

然后你可以按如下方式计算行数:

$res = mysql_query(select f.tag, count(f.tag) occurrences
from (
select id, tag1 as tag
from fruit
union
select id, tag2 as tag
from fruit
union
select id, tag3 as tag
from fruit
  ) f
group by f.tag
order by occurrences desc);

看看这个SQL小提琴来看看:

http://sqlfiddle.com/#!2/feb03/20

答案 1 :(得分:0)

类似于Reislef的建议,但在子查询中进行一些求和。这应该(希望)意味着子查询中的元素可以使用索引进行计数,并且大大减少了来自子查询的项目数,这些项目需要在子查询之外进行求和而不使用索引。

SELECT f.tag, SUM(f.tag_count) AS occurrences
FROM 
(
    SELECT tag1 AS tag, COUNT(*) AS tag_count
    FROM fruit
    GROUP BY tag
    UNION ALL
    SELECT tag2 AS tag, COUNT(*) AS tag_count
    FROM fruit
    GROUP BY tag
    UNION ALL
    SELECT tag3 AS tag, COUNT(*) AS tag_count
    FROM fruit
    GROUP BY tag
) f
GROUP BY f.tag
ORDER BY occurrences DESC

请注意,使用UNION ALL很重要(UNION会将重复项视为两个或更多列中计数相同的项目)