$query=$this->db->query('SELECT g.gallery_id, g.gallery_title, (
SELECT i.gallery_image_path
FROM nepal_gallery_image AS i
WHERE i.gallery_id = g.gallery_id
AND i.gallery_image_status = "Enabled"
LIMIT 0 , 1) AS gallery_image_path
FROM nepal_gallery AS g
WHERE g.gallery_status = "Enabled"');
上述查询提供了正确的输出。
但是,当我使用CI子查询库时:
$this->load->library('Subquery');
$this->db->select('g.gallery_id,g.gallery_title');
$sub = $this->subquery->start_subquery('select');
$sub ->select('i.gallery_image_path')
->from('nepal_gallery_image AS i')
->where(array('i.gallery_image_status'=>"Enabled",
'i.gallery_id'=>"g.gallery_id"))
->limit(0,1);
$this->subquery->end_subquery('gallery_image_path');
$this->db->from('nepal_gallery AS g');
$this->db->where('g.gallery_stats',"Enabled");
$query=$this->db->get();
生成的查询是:
SELECT `g`.`gallery_id` , `g`.`gallery_title` , (
SELECT `i`.`gallery_image_path`
FROM (`nepal_gallery_image` AS i)
WHERE `i`.`gallery_image_status` = 'Enabled'
AND `i`.`gallery_id` = 'g.gallery_id'
LIMIT 0 , 1 ) AS gallery_image_path
FROM (`nepal_gallery` AS g)
WHERE `g`.`gallery_status` = 'Enabled'
并且输出不符合预期。
第一个查询中的输出是
<table>
<tr>
<th> gallery_id</th>
<th> gallery_title</th>
<th> gallery_image_path </th>
</tr>
<tr>
<td>1</td>
<td>Gallery 1</td>
<td>images/image1.jpg</td>
</tr>
<tr>
<td>2</td>
<td>Gallery 2</td>
<td>images/image2.jpg</td>
</tr>
</table>
但是,在以后的查询中,输出是
<table>
<tr>
<th> gallery_id</th>
<th> gallery_title</th>
<th> gallery_image_path </th>
</tr>
<tr>
<td>1</td>
<td>Gallery 1</td>
<td>NULL</td>
</tr>
<tr>
<td>2</td>
<td>Gallery 2</td>
<td>NULL</td>
</tr>
</table>
似乎问题在于子查询。
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
问题在于条件将表格别名g
作为字符串'g.gallery_id'
的子查询避免CI保护字段的一种方法是将第三个参数作为false传递给where条件,这样CI就不会尝试用反引号保护你的字段或表名。
试试这个
$sub ->select('i.gallery_image_path')
->from('nepal_gallery_image AS i')
->where(array('i.gallery_image_status'=>"Enabled",
'i.gallery_id'=>"g.gallery_id"), NULL, FALSE);
//--^^^^^^^^^^^^^^--here
->limit(0,1);
或简单地写下你的条款manaully
$where = "i.gallery_id = g.gallery_id AND i.gallery_image_status = 'Enabled'";
$sub ->select('i.gallery_image_path')
->from('nepal_gallery_image AS i')
->where($where,NULL,FALSE);
->limit(0,1);
答案 1 :(得分:0)
->where(array('i.gallery_image_status'=>"Enabled",
'i.gallery_id'=>"g.gallery_id"))
问题在于'i.gallery_id'=&gt;“g.gallery_id” - CI正在使用“g.gallery_id”构建查询,因为它是一个文字字符串...当它是一个表列引用时。如果您手动将“g.gallery_id”替换为“g”。“gallery_id”,则应将其作为演示。
如果您不知道如何解决这个问题,请发表评论。 (这可能仅仅是使用单引号的问题。)