如何在cakephp 3中使用having子句写子查询

时间:2016-11-26 05:32:32

标签: mysql sql cakephp subquery cakephp-3.0

如何在CakePHP 3中编写以下查询。它在子查询中有“having”子句 以下查询正在运行但是编写CakePHP查询以执行以下复杂查询的方式是什么。

$query = "SELECT users.name, users.Id ,users.primary_image ,genders.name as genderName, FLOOR(DATEDIFF(CURDATE(),users.DOB) / 365) AS age, countries.Name as countryName, states.Name as stateName, 
user_log.online_status   
   FROM  users_address, genders , countries, states, user_log , users  
    WHERE gender_id = " . $looksFor->gender_id ."
AND Users_address.user_id = users.Id 
AND genders.Id = users.gender_id
AND Users_address.country_id = countries.Id
AND Users_address.state_id = states.Id
AND user_log.user_id = users.Id
AND users.Id IN (

SELECT users_responses.user_id
FROM users_responses
WHERE". $conditions_list ."
GROUP BY user_id
HAVING COUNT(DISTINCT question_id, response_id) > ".$thirty_percent." );
ORDER BY RAND()
LIMIT 15 ";
}

$ thirty_percent和$ conditions_list具有以下数据,在子查询中使用这些数据来查找结果。

$thirty_percent = (int)($conditions_count/3.3 );

$conditions_list = (question_id = 3 AND response_id = 6)OR
(question_id = 5 AND response_id = 8)OR
(question_id = 12 AND response_id = 33)OR
(question_id = 6 AND response_id = 17)OR
(question_id = 9 AND response_id = 26)OR
(question_id = 7 AND response_id = 18)OR
(question_id = 1 AND response_id = 5)OR
(question_id = 8 AND response_id = 22)OR
(question_id = 2 AND response_id = 3)

修改

我首先学习了写子查询,然后将该查询放入主查询

Main Query: $this->Users->find('all',[
    'contain'=>['Genders','Images','Users_Address', 'Countries','States'],
    'conditions'=>[ 'user_id IN' => $Subquery ]
    ]);

子查询:

$Subquery = $UsersResponses->find('all',[
    'conotain'=>[],
    ]])->where([$conditions_list, **here problem 1** ])->group('user_id')->having COUNT("(DISTINCT question_id, response_id)=>" = ".$thirty_percent." )here problem 2 ;


SQL sub-Query 

SELECT users_responses.user_id
    FROM users_responses
    WHERE". $conditions_list ."
    GROUP BY user_id
    HAVING COUNT(DISTINCT question_id, response_id) > ".$thirty_percent." );
    ORDER BY RAND()
    LIMIT 15 ";

   As you see in sub-query I need to put $conditions_list which have arrays of conditions and how we can put here in CAKEPHP.


problem 2 :need to use 
GROUP BY user_id
HAVING COUNT(DISTINCT question_id, response_id) > ".$thirty_percent." );
ORDER BY RAND()
LIMIT 15 "; in sub-query but there is no clue how to do it. 

0 个答案:

没有答案