CodeIgniter Active记录子查询中的位置

时间:2017-09-08 02:34:13

标签: php mysql codeigniter activerecord

如何使用codeigniter活动记录在where_in语句中编写子查询?

$query = $this->db->query("SELECT SUM(a.transaction_payment_amount) FROM 
         transaction_payment a WHERE a.transaction_link IN 
         (SELECT transaction_link FROM transaction WHERE transaction_type = '22'");
$result = $query->result();

现在如何将上述查询转换为CI活动记录?

我试过了:

$this->db->select("SUM(a.transaction_payment_amount)");
$this->db->from('transaction_payment a');
$this->db->where_in('a.transaction_link', "SELECT transaction_link from transaction WHERE transaction_type = '22'");
$query = $this->db->get();
$result = $query->result();

但它没有用。

3 个答案:

答案 0 :(得分:1)

试试这个

$this->db->where_in('a.transaction_link', "SELECT transaction_link from transaction WHERE transaction_type = '22'",false);

如果您使用false,则会从where_in条件

中删除单引号

答案 1 :(得分:1)

Sharmas答案应该完成这项工作,但如果您希望完全支持的查询生成器方法,您可以尝试这个

$strSubQuery = $this->db
    ->select("transaction_link")
    ->from("transaction")
    ->where("transaction_type",22)
    ->get_compiled_select();

$query = $this->db
    ->select("SUM(a.transaction_payment_amount)", false)
    ->from('transaction_payment a')
    ->where_in('a.transaction_link', $strSubQuery, false)
    ->get();

答案 2 :(得分:0)

您可以将代码更改为以下解决方案。

  

更改您的查询

$this->db->select("SUM(a.transaction_payment_amount)");
$this->db->from('transaction_payment a');
$this->db->where("a.transaction_link IN (SELECT transaction_link from transaction WHERE transaction_type = '22')", null, false);
//OR you can try other where condition if Sub query return null value than used this below query
$this->db->where("IF(SELECT transaction_link from transaction WHERE transaction_type = '22',a.transaction_link IN (SELECT transaction_link from transaction WHERE transaction_type = '22'), NULL)", null, false);
$query = $this->db->get();
$result = $query->result();

我希望这会对你有所帮助。谢谢!