如何从同一个表MySQL的多个列中计算一个事件?

时间:2014-03-30 10:42:29

标签: php mysql sql count

我希望计算5个列中我的表中使用最多的前5个关键字。

所以我的表格是网站,我的列是"site_motclef1", "site_motclef2", "site_motclef3", "site_motclef4" and "site_motclef5"

我知道如何逐列找到最多使用过的关键字,但我想计算所有5列中的总数。

这就是我发现只在一列中计算的方式=>

SELECT COUNT( * ) total, site_motclef1
FROM sites
WHERE  `site_active` =  'Yes'
GROUP BY site_motclef1
ORDER BY  `total` DESC 
LIMIT 0 , 5

有人可以开车送我?

谢谢:)

我是这样尝试的,但那不能给我一个正确的结果:/ 也许我的方式很好?

select count(*) total, site_motclef
from (
  select site_motclef1 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION
  select site_motclef2 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION
  select site_motclef3 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION
  select site_motclef4 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION
  select site_motclef5 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
) AS X
ORDER BY total DESC

2 个答案:

答案 0 :(得分:0)

在列名中包含数字几乎都是由于数据库设计错误造成的。您可以通过添加2个与sites表相关的新表来解决此问题。

motclef table
-------------
id
name


site_motclef table
------------------
site_id
motclef_id

然后你可以找到这样的前5个关键词

select m.name, count(ms.motclef_id) as total_count
from motclef m
join motclef_site ms on ms.motclef_id = m.id
group by m.name

此设计还可以为每motclef个提供超过或少于5 site的内容。

答案 1 :(得分:0)

虽然我完全同意Juergen的意见,你应该通过为每个关键字和网站分别设置一个单独的表来修复数据库设计,但是查询的问题是union而缺少group by 。它正在删除重复项。您需要将其替换为union all

select count(*) total, site_motclef
from (
  select site_motclef1 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION ALL
  select site_motclef2 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION ALL
  select site_motclef3 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION ALL
  select site_motclef4 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
  UNION ALL
  select site_motclef5 as site_motclef FROM sites WHERE  `site_active` =  'Yes'
) AS X
group by site_motclef
ORDER BY total DESC;

如果您只想要5,那么请将limit 5添加到最后。