2017-03-15 57 views
1

我有一个场景,我有表名为组和论坛。在该组中,我想要以降序显示在该组内创建的最大论坛的5个组。现在的问题是,我有计算每个组中有多少个论坛,现在的主要问题是我很困惑如何获得该组的数据。谁能帮我吗 ?获得第二张桌子的ID号

<?php 
    $sql_gr_coun = $this->db->query("SELECT groups.*, (SELECT count(group_id) FROM forums WHERE groups.id = forums.group_id) as forumcount FROM groups ORDER BY forumcount DESC LIMIT 5"); 
    foreach($sql_gr_coun->result() as $data_count): 
     $sql_grp = $this->db->get_where('groups', array('id' => $data_count->group_id)); 
    endforeach; 
?> 


Groups 
+----+----------+ 
| id | name  | 
+----+----------+ 
| 1 | group 1 | 
| 2 | group 2 | 
| 3 | group 3 | 
| 4 | group 4 | 
+----+----------+ 

forums 
+------------------+-------------+ 
| id | title  | group_id | 
+------------------+-------------+ 
| 1 | test 1  |   2 | 
| 2 | test 2  |   3 | 
| 3 | test 3  |   2 | 
| 4 | test 4  |   3 | 
| 5 | test 5  |   2 | 
| 6 | test 6  |   4 | 
+------------------+-------------+ 

由于我无法现在该怎么做呢

+1

获得组ID ,将它发送给某个模型函数并返回数据 –

+0

我如何获得群组ID,其中有更多的论坛经历循环第一组ID为3和第二组ID为2,所以如何获得3论坛组信息和2论坛组信息? –

+0

你能分享你的数据库模式吗? ?你的表结构? –

回答

1

当你在你的查询SELECT组写的。*,你已经与相处组数据来获得各组的数据你要ID,还有什么做

+0

非常感谢它为我工作 –

1

这似乎是对组ID和groupsforums表和一组之间的简单连接数的记录数:

select groups.id, count(*) as forum_count 
from groups 
left join forums on groups.id = forums.group_id 
group by groups.id 

如果您想从groups表中获取所有字段,而不仅仅是id,那么在MySQL v5.7及更高版本中,您可以使用以下语句,因为groups表中的所有字段值在功能上都依赖于id字段:

select groups.*, count(*) as forum_count 
from groups 
left join forums on groups.id = forums.group_id 
group by groups.id 

在早期版本中,如果启用了由SQL模式整组,你需要使用一个子查询或列表列出从groups表中的所有字段组:

select groups.*, count(*) as forum_count 
from groups 
left join forums on groups.id = forums.group_id 
group by groups.id,... --list all fields from the groups table here 
+0

如果我想放置一个条件并检查此组ID和user_id不存在于组成员表中,您可以在这里回答,还是应该发布另一个问题? –

+0

所有新问题都应该作为一个新问题提出。你可以参考新的问题。 – Shadow

相关问题