在codeigniter中只有一个查询,是否有可能对特定的id计数和从另一个表中减去?

时间:2018-02-14 05:07:30

标签: php mysql codeigniter

我希望从clinic_id表计算sms_history行,并在一个查询中从total_available_sms表中的sms sms列中减去。

sms_history表 [sms_history table

短信表 sms table

用户表 users table

我想在表格中显示记录:

Client Id  Client Name           Available sms   Total SMS
---------  -------------------   --------------  ---------
2          Krishna Dental Care   196             200

我正在尝试做这样的事情

$this->db->select('*');
$this->db->from('sms');
$query = $this->db->get();
$total_available = $query->result();


foreach ($total_available as $sms) {

//get clinic id
$clinic_id = $sms->clinic_id;

//get total available sms
$total_available = $sms->total_available;

$count = $this->db->where('clinic_id',$clinic_id)->from("sms_history")->count_all_results();

//get finaly count sms
$final_count_sms = $total_available - $count;


// get clinics from user table
$this->db->where('clinic_id', $clinic_id);
$q = $this->db->get('users');
$data = $q->result_array();

// get clinic name
$clinic_name = $data[0]['clinic_name'];

}

1 个答案:

答案 0 :(得分:1)

是的,可以在一个查询中使用:

尝试以下查询:

SELECT ( SELECT total_available FROM sms WHERE clinic_id = '1' ) - COUNT( sms_history.clinic_id) FROM sms_history JOIN sms ON sms_history.clinic_id= sms.clinic_id 

如果您有多个ID,请执行以下操作,

你有clinc_id sms_history是1,2。

所以你可以把它做成数组:

$ids = array('1','2');
for($i = 0 ; $i <= $ids.length; $i++)
{

      $sql = "SELECT ( SELECT total_available FROM sms WHERE clinic_id = '".$ids[i]."' ) - COUNT( sms_history.clinic_id) FROM sms_history JOIN sms ON sms_history.clinic_id= sms.clinic_ids WHERE sms_history.clinic_id =  '".$ids[i]."'";
      /* after your generate your query you will get substration of it. so at same time you need to fire update query for "available_message" */

}

尝试上面的代码我希望这对你有用。