在codeigniter中编写查询,给出与所需结果不同的结果

时间:2012-08-18 14:46:21

标签: codeigniter

我正在开发codeigniter,我正在编写以下查询:

$this->db->select('*');
$this->db->from('tbl_profile');
$this->db->join('tbl_msg', 'tbl_msg.msg_sender_id = tbl_profile.profile_id');
$this->db->order_by("msg_id", "desc");
$query = $this->db->get('', $config['per_page'], $this->uri->segment(3));
$data['records'] = $query->result_array();

相应地,我得到以下结果:

SELECT (*) FROM tbl_profile
JOIN tbl_msg ON tbl_msg.msg_sender_id = tbl_profile.profile_id

由于我希望结果对应于以下查询,因此返回错误的结果:

select * from tbl_profile as A
join (select * from tbl_msg) as B on A.profile_id = B.msg_sender_id

请帮忙

1 个答案:

答案 0 :(得分:0)

首先,你错过了order by子句,但我认为,你的意思是其他差异。

如果您需要,可以使用此查询,这将为您提供确切的代码:

$this->db->select('*', FALSE);
$this->db->from('tbl_profile as A');
$this->db->join('( select * from tbl_msg ) as B', 'A.msg_sender_id = B.profile_id');
$this->db->order_by("msg_id", "desc");
$query = $this->db->get('', $config['per_page'], $this->uri->segment(3));
$data['records'] = $query->result_array();

来自codeigniter用户手册:

$this->db->select()

接受可选的第二个参数。如果将其设置为FALSE,CodeIgniter将不会尝试使用反引号来保护您的字段或表名称。如果您需要复合选择语句,这非常有用。