Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 从同一表的多个列按计数排序_Mysql_Sql - Fatal编程技术网

Mysql 从同一表的多个列按计数排序

Mysql 从同一表的多个列按计数排序,mysql,sql,Mysql,Sql,所以,我在posts表中有以下列:球队id、球员id、联赛id、教练id、场地id。任何给定的post都可以在每列上有一组id 现在,我想按任何id的DESC计数订购。 例如:结果应该是: 3-联盟id//因为它的总数为3 7-团队id//因为它总共计2个 8-player_id//因为它的计数为2,以此类推 基本上,我们按count DESC排序,但它必须是同一列的count 我能得到它吗?它还必须给我列名,以便我知道该列的id。 谢谢大家! 适当的数据模型将为每个关系提供单独的连接/关联表

所以,我在posts表中有以下列:球队id、球员id、联赛id、教练id、场地id。任何给定的post都可以在每列上有一组id

现在,我想按任何id的DESC计数订购。 例如:结果应该是:
3-联盟id//因为它的总数为3
7-团队id//因为它总共计2个
8-player_id//因为它的计数为2,以此类推

基本上,我们按count DESC排序,但它必须是同一列的count
我能得到它吗?它还必须给我列名,以便我知道该列的id。
谢谢大家!

适当的数据模型将为每个关系提供单独的连接/关联表:

  • post_团队
  • post\u播放器
  • post_联赛
  • post\u coach
  • post_场馆
每一个表都将正确地声明与两个引用表的外键关系

使用这种模型,您的查询实际上非常简单:

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有一个很好的存储列表的方法。它被称为表,而不是字符串。

列的数据类型是什么?为什么要在一列中存储多个值?这不是关系数据库的最佳数据模型。你确定你在使用MySQL吗?有些数据库支持数组类型,但MySQL不是其中之一。@GordonLinoff数据类型是文本。我在post中为基本标记的项存储多个值。是的,是MySQL。我建议您使用多个关联/连接表来修复数据模型,而不是试图找出如何做到这一点。处理糟糕的数据模型是不值得的。