Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.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
如何使用嵌套模型进行复杂的SQL查询?_Sql_Ruby On Rails_Activerecord_Ruby On Rails 4 - Fatal编程技术网

如何使用嵌套模型进行复杂的SQL查询?

如何使用嵌套模型进行复杂的SQL查询?,sql,ruby-on-rails,activerecord,ruby-on-rails-4,Sql,Ruby On Rails,Activerecord,Ruby On Rails 4,我有三种型号: 频道节目插曲 Channel has_many programs Program belongs_to channel Program has_many episodes Episode belongs_to program 如何进行此查询 *“相关频道的总集数s,其中节目数最高。* 更详细地说, 查找节目数最多的频道 查找与属于该频道的节目合并的剧集数 我真的累坏了 如何最有效地执行此操作,而不是编写代码行和许多查询?我不知道如何使用active record。但您可以使用s

我有三种型号:
频道
节目
插曲

Channel has_many programs
Program belongs_to channel
Program has_many episodes
Episode belongs_to program
如何进行此查询

*“相关
频道的
集数
s,其中
节目数最高。*

更详细地说,

  • 查找节目数最多的频道
  • 查找与属于该频道的节目合并的剧集数
  • 我真的累坏了


    如何最有效地执行此操作,而不是编写代码行和许多查询?

    我不知道如何使用active record。但您可以使用sql解决此问题

    比如说

    select top 1 c.channel_id, count(p.)  as count from Program as p inner join Channels as c on c.channel_id=p.channel_id group by  c.channel_id order by 2 desc
    

    sql server、mysql、oracle?@Mihai活动记录查询独立于数据库,对吗?@emaillenin坦率地说,我不知道什么是活动记录。它是postgresql@Mihai。即使使用sql,任何帮助都是值得赞赏的。所以你想找到节目数量最多的频道的总剧集数吗?你想在哪里进行处理许多频道都有最多的节目,但可能有不同的插曲数?