下一个/上一个分页查询参数php mysql带参数

时间:2012-11-19 21:51:23

标签: php mysql

我有以下问题:这是我的表enter image description here

的结构

enter image description here

这是我的代码:

            $SQL_NEXT_PROJECT_ID ="SELECT id  FROM projects WHERE id < '".$id_project."' and project_types_id='".$project_type_id."' ORDER BY id DESC LIMIT 1";
            $conn->query($SQL_NEXT_PROJECT_ID);
            foreach ($conn->query($SQL_NEXT_PROJECT_ID) as $rowProjectNext) {
                $next_project_id = $rowProjectNext['id'];
            }

            $SQL_PREVIOUS_PROJECT_ID ="SELECT id  FROM projects WHERE id > '".$id_project."' and project_types_id='".$project_type_id."' ORDER BY id ASC LIMIT 1";
            $conn->query($SQL_PREVIOUS_PROJECT_ID);
            foreach ($conn->query($SQL_PREVIOUS_PROJECT_ID) as $rowProjectPrevious) {
                $previous_project_id = $rowProjectPrevious['id'];
            }

问题是我需要从'images'表中添加一个aditional条件的查询我必须评估main field ='1',我一直试图用内连接来做它但看起来并不像工作,在这里我附上我一直在尝试的查询

$SQL_NEXT_PROJECT_ID ="SELECT projects.id  FROM projects INNER JOIN images WHERE projects.id > '".$id_project."' and project_types_id='1' and main='1' ORDER BY projects.id DESC LIMIT 1";

基本上我需要做的是根据项目的当前id($ id_project)创建下一个/上一个指向某个类型项目的链接($ id_project),同时考虑到项目应该有一个图像主要字段等于'1'

希望我能很好地解释自己......

2 个答案:

答案 0 :(得分:0)

嗯,你没有加入任何东西......你需要一个ON条款。

SELECT pr.id  FROM projects pr 
INNER JOIN images img ON (pr.id = img.projects_id AND img.main = 1)
WHERE pr.id > ? 
AND pr.project_types_id = 1 
ORDER BY pr.id DESC LIMIT 1

答案 1 :(得分:0)

最后我这样做了

$_nextPrevious = array();

            $SQL_SEARCH_VALUES="SELECT images.projects_id AS projectId FROM projects INNER JOIN images ON ( projects.id = images.projects_id ) AND project_types_id =  '".$project_type_id."' AND images.main =  '1' LIMIT 0 , 30";
            $conn->query($SQL_SEARCH_VALUES);
            foreach($conn->query($SQL_SEARCH_VALUES) as $rowNextPrevious) {
                $value = $rowNextPrevious['projectId'];                    
                array_push($_nextPrevious, $value);
            }


            $currentValue = array_search($id_project, $_nextPrevious);

            $next = $currentValue + 1;

            $previous = $currentValue - 1;

            $next_project_id = $_nextPrevious[$next];

            $previous_project_id = $_nextPrevious[$previous];

            return array($project_name,$project_description,$project_path, $_images, $next_project_id, $previous_project_id);

使用数组而不是两次搜索......