我正在尝试将嵌套查询转换为codeigniter上的活动记录。
我的查询:
SELECT COUNT(*) AS count, snapshot_id, snapshot_guid, image, subject, name, brands.brand_id, brand_guid, date_sent FROM
(SELECT snapshot_id, snapshot_guid, snapshots.brand_id, image, subject, snapshots.status, date_sent
FROM snapshots INNER JOIN brands ON snapshots.brand_id = brands.brand_id
WHERE (snapshots.status = 1 AND brands.status = 1) AND DATE(date_sent) = '2015-2-9'
ORDER BY date_sent DESC) snapshots
INNER JOIN brands
ON snapshots.brand_id = brands.brand_id
GROUP BY snapshots.brand_id
ORDER BY date_sent DESC;
它产生了正确的结果,但似乎无法正常工作。
这是我到目前为止所做的:
if(is_null($date))
$date = date('Y-m-d');
/* sub query */
$this->db->select('snapshot_id, snapshot_guid, image, snapshots.brand_id, subject, snapshots.status, date_sent');
$this->db->from('snapshots');
$this->db->join('brands', 'snapshots.brand_id = brands.brand_id', 'inner');
$this->db->where('snapshots.status', 1);
$this->db->where('brands.status', 1);
$this->db->where('DATE(date_sent)', $date);
$this->db->order_by('date_sent', 'desc');
$this->db->get();
$sub = $this->db->last_query();
$this->db->select('count(*) as count, snapshot_id, snapshot_guid, image, name, snapshots.brand_id, brand_guid, date_sent')
//$this->db->from($sub, null, false);
$this->db->join('brands', 'snapshots.brand_id = brands.brand_id', 'inner');
$this->db->where('brands.status', 1);
$this->db->group_by('snapshots.brand_id');
$this->db->order_by('date_sent', 'desc');
$this->db->limit($count);
$query = $this->db->get($sub.' as snapshots');
return $query->result();
错误在于:$ query = $ this-> db-> get($ sub .'as snapshots');
它在子查询中添加了一个额外的撇号。例如:
FROM (`SELECT` `snapshot_id`, `snapshot_guid`, `image`, `snapshots`.`brand_id`, `subject`, `snapshots`.`status`, `date_sent` FROM` (`snapshots`) INNER JOIN `brands` ON `snapshots`.`brand_id` = `brands`.`brand_id` WHERE `snapshots`.`status` = 1 AND `brands`.`status` = 1 AND DATE(date_sent) = '2015-2-9' ORDER BY `date_sent` desc as snapshots) INNER JOIN `brands` ON `snapshots`.`brand_id` = `brands`.`brand_id` WHERE `brands`.`status` = 1 GROUP BY `snapshots`.`brand_id` ORDER BY `date_sent` desc LIMIT 10
正如您所看到的,SELECT位于后撇号的
之内答案 0 :(得分:0)
我建议你先group your code。编写另一个函数subQuery,然后从那里执行你的mainQuery。
示例:
Class Example_model Extends CI_Model
{
function subQuery()
{
$query = "SELECT value_2 FROM other_table WHERE id = 2";
$q = $this->db->query($query);
$this->mainQuery($q->result());
}
function mainQuery($subQuery)
{
$query = "UPDATE some_table SET value_1 = "'.$subQuery.'" WHERE id = 2";
$this->db->query($query);
}
}
阅读CodeIgniter User Guide后,声明:
$这 - > DB->得到();
运行选择查询并返回结果。可以单独使用 检索表中的所有记录
我认为你必须在引号中包含$ sub变量。