使用codeigniter进行多个/子查询

时间:2012-07-09 03:12:30

标签: php sql codeigniter

我刚开始使用Codeigniter,这让我疯狂。我有一个查询,确定用户是否购买了任何程序。然后我必须使用该程序的类型类别来运行并确定他或她在另一个表中记录查询的次数。很抱歉混乱,但代码希望是有道理的。

我遇到了将两个数组从我的模型返回到我的控制器到显然的问题的问题。

function specificPrograms() {
$specific_sql = $this->db->query("SELECT program,created FROM  `assessment`  WHERE uid = $this->uid");
if($specific_sql->num_rows() > 0) {
foreach ($specific_sql->result() as $specific) {        
$data[] = $specific;
$this->type = $specific->program;   
}
return $data;
}   

$sub_sql = $this->db->query("SELECT id FROM othertable WHERE user_id_fk = $this->uid and type = '$this->type'");
if($sub_sql->num_rows() > 0) {
foreach ($sub_sql->result() as $otherp) {       
$data[] = $otherp;
}
return $data;
}

}

然后在我的控制器中,我有,

$data['specific'] = $this->user_model->specificPrograms();
$data['otherp'] = $this->user_model->specificPrograms();

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

根据您上面的评论,我建议一个查询返回您需要的结果。结果集如下所示:

+----------+------------+------+
| program  | created    | uses |
+----------+------------+------+
| football | 2001-01-01 | 12   |
+----------+------------+------+
| baseball | 2007-01-01 | 21   |
+----------+------------+------+


SELECT 
  assessment.program, 
  assessment.created, 
  count(othertable.user_id) as uses
FROM  assessment
JOIN othertable 
  ON othertable.user_id_fk = assessment.uid
  AND othertable.type = assessment.program
WHERE assessment.uid = $this->uid
GROUP BY assessment.program

... model ...

function specificPrograms() {
  $results = $this->db->query($sql_from_above);
  if($specific_sql->num_rows() > 0) {
  foreach ($specific_sql->result() as $program_data) {        
    $data[] = $program_data;
  }
  return $data;
}

... meanwhile in controller ...


$programs_used = $this->user_model->specificPrograms();
foreach($programs_used as $program_use_data) {
  // On first iteration, this is true:
  // $program_use_data['program'] == "football"
  // $program_use_date['uses'] == 12
}