获取MySQL中多个字段的计数

时间:2018-06-27 06:33:25

标签: php sql codeigniter

enter image description here我无法通过下面的此SQL查询从3个不同的表中获得3个计数字段。有人可以帮我解决我误会的地方。第一个计数分配给另外两个字段。意味着如果我将“ total_scenarios”计数为10,则其余2个选项(total_career_sketches,video_count)的值都为10。

$this->db->select('users.id,users.name,users.user_lname,users.email, 
count(fc_scenarios.user_id) as total_scenarios, count(career_sketch.user_id) 
as total_career_sketches, count(video_tracker.user_id) as video_count 
,career_timeline.filled_modules');
$this->db->from('users');
$this->db->join('fc_scenarios','users.id = fc_scenarios.user_id AND 
fc_scenarios.status = "A" AND fc_scenarios.type = "o"','left');
$this->db->join('career_sketch','users.id = career_sketch.user_id AND 
career_sketch.status = "A" AND career_sketch.type = "o"','left');
$this->db->join('video_tracker','users.id = video_tracker.user_id','left');
$this->db->join('career_timeline','users.id = 
career_timeline.user_id','left');
$this->db->where('users.inkwiry_user != ',1);
$this->db->where('users.status','A');
$this->db->group_by('users.id');

谢谢, 卫星

2 个答案:

答案 0 :(得分:2)

您可能需要为连接的表计算不同的值,我猜由于一对多的关系,由于连接,您会得到多行重复的行,我建议您在

之类的内部使用count函数
$this->db->select('users.id,users.name,users.user_lname,users.email, 
count(distinct fc_scenarios.id) as total_scenarios, 
count(distinct career_sketch.id) as total_career_sketches, 
count(distinct video_tracker.id) as video_count,
career_timeline.filled_modules')

您的查询也是无效的,因为group by子句在组行中只有一列,但是在选择列表中,您也试图选择不包括在group by中且也不聚合的其他列

答案 1 :(得分:1)

您可以尝试以下查询,它将起作用

$this->db->select('users.id,users.name,users.user_lname,users.email, 
count(distinct fc_scenarios.id) as total_scenarios, count(distinct career_sketch.id) 
as total_career_sketches, count(distinct video_tracker.id) as video_count 
,career_timeline.filled_modules');
$this->db->from('users');
$this->db->join('fc_scenarios','users.id = fc_scenarios.user_id AND 
fc_scenarios.status = "A" AND fc_scenarios.type = "o"','left');
$this->db->join('career_sketch','users.id = career_sketch.user_id AND 
career_sketch.status = "A" AND career_sketch.type = "o"','left');
$this->db->join('video_tracker','users.id = video_tracker.user_id','left');
$this->db->join('career_timeline','users.id = 
career_timeline.user_id','left');
$this->db->where('users.inkwiry_user != ',1);
$this->db->where('users.status','A');
$this->db->group_by('users.id');