【发布时间】:2015-02-11 05:25:20
【问题描述】:
我正在尝试将嵌套查询转换为 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 在后面的撇号内
【问题讨论】:
标签: php mysql codeigniter activerecord