【发布时间】:2017-12-09 02:46:04
【问题描述】:
我正在开发search 功能。
我创建了一个搜索表单,用户可以在其中搜索基于Type、ope 和Formate 的应用程序。
我在 join 查询中使用了 子查询 来获得所需的结果。
我已经在MySQL Workbench 中测试了我的查询,它工作正常。
但是当我使用查询构建器技术在 Codeigniter 中尝试相同的查询时,我遇到了问题。
这是在工作台中运行良好的查询:
SELECT (*)
FROM `App`
LEFT JOIN `App_type`
ON `App_type`.`app_id` = `App`.`id`
LEFT JOIN `App_formate`
ON `App_formate`.`app_id` = `App`.`id`
WHERE `App`.`id` IN(select app_id FROM App_type WHERE type_id in (3,2,6) group by app_id HAVING COUNT(*) = 3)
AND `App_formate`.`formate_id` IN('1', '3')
AND `jobs`.`ope_min` <= '3'
AND `jobs`.`ope_max` >= '3'
GROUP BY `jobs`.`id`;
这是我使用的连接查询:
$subquery = "select app_id FROM App_type WHERE type_id in ($selected_type) group by app_id HAVING COUNT(*) = $type_count";
$search_app_query = $this->db
->select('*')
->from('App')
->join('App_type', 'App_type.app_id = App.id', 'left outer')
->join('App_formate', 'App_formate.app_id = App.id', 'left outer')
->where_in('App.id',$subquery) //<-- Here is the problem
->where_in('App_formate.formate_id',$data['selected_formates'])
->where('App.ope_min <=',$data['ope_value'])
->where('App.ope_max >=',$data['ope_value'])
->group_by("App.id", "desc")
->get();
当我调试这个问题时,它显示了
I have found the problem is in this part of the query:
"WHERE `App`.`id` IN('select app_id
FROM App_type
WHERE type_id in (3,2,6)
group by app_id HAVING COUNT(*) = 3')"
此子查询中的单引号造成了问题。
到目前为止我所尝试的:
我试过删除这个单引号
-
REPLACE($subquery, '''', '') ->where_in('App.id',trim($subquery,"'"))-
$subquery_improved = substr($subquery, 1, -1);
但是所有这些解决方案都不起作用。他们没有删除单引号。
注意:我知道$this->db->query(),但不想使用它。
【问题讨论】:
-
我不熟悉框架——尤其是如何将该子查询作为 实际子查询传递。 但是,如果文档没有明确说明,并且如果子查询的结果不是压倒性的,只需自行执行它并将结果传递到:
where_in('App.id', $subquery_results)。我假设$subquery_results需要是array。 -
@svidgen 我知道 where_in 需要数组,但唯一的问题是
$subquery开头和结尾处的单引号,顺便感谢您的建议。 -
尝试使用 echo $this->get_compiled_select() 并查看构建的查询是什么
-
我已经做到了,我得到了问题所在但没有得到解决方案,我想我必须给它一个赏金。
-
你可以试试
where_in('App.id',$subquery)而不是where("App.id IN (".$subquery.")",NULL, false)
标签: php mysql codeigniter