mysql count多个字段,MySQL COUNT()多列

本文介绍如何从数据库中包含多个标签的视频表中,忽略空值并汇总各非空标签的流行度,同时获取对应的'flv'信息。通过 SQL 聚合和 UNION ALL 技巧,实现多列数据的单列处理,以便按流行度排序和限制展示结果。
摘要由CSDN通过智能技术生成

I'm trying to fetch the most popular tags from all videos in my database (ignoring blank tags). I also need the 'flv' for each tag. I have this working as I want if each video has one tag:

SELECT tag_1, flv, COUNT(tag_1) AS tagcount

FROM videos

WHERE NOT tag_1=''

GROUP BY tag_1

ORDER BY tagcount DESC LIMIT 0, 10

However in my database, each video is allowed three tags - tag_1, tag_2 and tag_3. Is there a way to get the most popular tags reading from multiple columns?

The record structure is:

+-----------------+--------------+------+-----+---------+----------------+

| Field | Type | Null | Key | Default | Extra |

+-----------------+--------------+------+-----+---------+----------------+

| id | int(11) | NO | PRI | NULL | auto_increment |

| flv | varchar(150) | YES | | NULL | |

| tag_1 | varchar(75) | YES | | NULL | |

| tag_2 | varchar(75) | YES | | NULL | |

| tag_3 | varchar(75) | YES | | NULL | |

+-----------------+--------------+------+-----+---------+----------------+

解决方案

You need to unpivot the data:

SELECT tag, COUNT(*)

FROM (

SELECT tag_1 AS tag

UNION ALL

SELECT tag_2 AS tag

UNION ALL

SELECT tag_3 AS tag

) AS X (tag)

GROUP BY tag

ORDER BY COUNT(*) DESC

I'm not sure how the flv is determined for a particular tag, since each id can have a single flv and up to 3 tags, it seems like any tag can have many different flv.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值