简体   繁体   English

Codeigniter活动记录选择,左联接,计数

[英]Codeigniter active record select, left join, count

I have a form that shows results from a database query, these results can have many other assets ajoined to them and I wanting to find a way of showing how many assets each elemement has. 我有一个显示数据库查询结果的表格,这些结果可以与许多其他资产关联在一起,我想找到一种显示每个元素有多少资产的方法。 For example my table is of areas of england an other table has where the users live I current have this code, 例如,我的桌子是英国地区,另一个桌子是用户居住的地方,我目前有此代码,

$this->db->select('*');
$this->db->from('places');
$this->db->join('users, places.place_id = user.place_id, left');

$this->db->get();

The issue I am having is getting the query to return the place name and the number of users living in that place, it is possible? 我遇到的问题是查询返回地名和居住在该位置的用户数,这可能吗?

Not knowing your exact db setup, but something like this is how you would do this query using CodeIgniter's Active Record 不知道确切的数据库设置,但是类似的事情就是您如何使用CodeIgniter的Active Record执行此查询

 $this->db->select('places.place_id');
 $this->db->select_sum('places.place_id', 'total');
 $this->db->from('places');
 $this->db->join('users', 'places.place_id = user.place_id', 'left');
 $this->db->group_by('user.place_id');
 $this->db->get();
select places.place_id,
       count(*) as UsersAtThisPlace
   from
       places,
       users
   where 
       places.place_id = users.place_id
   group by
       places.place_id

Don't know exactly how to implement via your PHP, but it should be as simple as the above query all within your 不知道确切如何通过您的PHP实现,但它应该与上述查询一样简单

$this->db->select( "entire string example above" ); $ this-> db-> select(“以上整个字符串示例”);

Additionally, if you had other descriptive elements from the places table, you could add those as well before the count (just for clarity), but would also have to include them in the group by... such as 另外,如果您在places表中还有其他描述性元素,则可以在计数之前也添加这些描述性元素(为了清楚起见),但是还必须将它们包括在组中,例如:

select places.place_id,
       places.description,
       places.otherfield,
       count(*) as UsersAtThisPlace
   from
       places,
       users
   where 
       places.place_id = users.place_id
   group by
       places.place_id,
       places.description,
       places.otherfield

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM