[英]Order by count from multiple columns of same table
所以,我在帖子表中有以下几列:team_id、player_id、league_id、coach_id、venue_id。任何给定的帖子在每一列上都可以有一堆id。
现在,我想按任何 id 的 DESC 计数进行排序。 例如:结果应该是:
3 - League_id //因为它的总数为 3
7 - team_id // 因为它的总数为 2
8 - player_id //因为它的计数为 2,依此类推。
基本上,我们按计数 DESC 排序,但它必须来自相同的列数。
我有什么办法可以得到吗? 它还必须给我列名,以便我知道该列的 ID。 谢谢!
正确的数据模型将为每个关系提供单独的连接/关联表:
post_teams
post_players
post_leagues
post_coaches
post_venues
这些中的每一个都将正确声明与两个引用表的外键关系。
使用这样的模型,您的查询实际上非常简单:
select which, id, count(*)
from ((select post_id, team_id as id, 'team' as which
from post_teams
) union all
(select post_id, players_id as id, 'players' as which
from post_players
) union all
(select post_id, leagues_id as id, 'leagues' as which
from post_leagues
) union all
(select post_id, coach_id as id, 'coach' as which
from post_coaches
) union all
(select post_id, venue_id as id, 'venue' as which
from post_venues
)
) x
group by which, id
order by count(*) desc;
我建议你修复你的数据模型——或者切换到一个对数组有本机支持的数据库。 MySQL 有一个很好的方法来存储列表。 它被称为表,而不是字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.