Отдельный запрос не дает результатов с оператором AND - PullRequest
0 голосов
/ 28 мая 2019

Вот запрос, который я пытаюсь выполнить, но я не получаю результатов, если вам нужна дополнительная информация, чтобы помочь в этом вопросе, пожалуйста, в комментариях ниже, я был бы признателен за любую помощь. Спасибо.

SELECT DISTINCT * FROM <code>users ГДЕ ((height МЕЖДУ «139» И «170» И language = «АНГЛИЙСКИЙ») И (active = «1» И gender В (4525,4526) И DATEDIFF (CURDATE (), birthday) / 365> = "22" И DATEDIFF (CURDATE (), birthday) / 365 <= "55" И <code>country = "IT") И id НЕ ВХОДИТ ( ВЫБРАТЬ block_userid ОТ blocks ГДЕ user_id = 1) И id НЕ ВХОДИТ (ВЫБРАТЬ like_userid ОТ likes ГДЕ user_id = 1) И id НЕ ВХОДИТЬ (ВЫБРАТЬ user_id ОТ likes WHERE like_userid = 1) И id <> "1") ЗАКАЗАТЬ ПО xlikes_created_at DESC, xvisits_created_at DESC, xmatches_created_at DESC, is_pro DESC LIMIT 12 OFFSET 0;

Я пробовал оператор ИЛИ, но, конечно, я не ищу ИЛИ, я хочу, чтобы все условия выполнялись, а затем хотел получить результаты.

function GetSearchResults($user_id, $limit, $offset, $country = true){
$where_or = array();
$where_and = array();
$u = auth();
// main query
$query = 'SELECT DISTINCT * FROM `users`';
// Filters
$where = ' WHERE ( ';
// must be verified
$where_and[] = '`active` = "1"';
//$where_and[] = '`privacy_show_profile_match_profiles` = "1"';
//********** public search params *****************//
// check gender from post or from session
$genders = null;
if( isset($_SESSION['_gender']) && $_SESSION['_gender'] !== ''){
    $genders = Secure( $_SESSION['_gender'] );
}
if( isset($_POST['_gender']) && $_POST['_gender'] !== ''){
    $_SESSION[ '_gender' ] = $_POST['_gender'];
    $genders = Secure( $_POST['_gender'] );
}
if( $genders == null || $genders == 'male' || $genders == 'female' ){
    $genders = '4525, 4526';
}
if( is_array($genders) ){
    $genders = @implode( ',' , $genders );
}
if( strpos( $genders, ',' ) === false ) {
    $where_and[] = '`gender` = "'. $genders .'"';
}else{
    $where_and[] = '`gender` IN ('. $genders .')';
}
// check age from post or from session
if( isset($_POST['_age_from']) && !empty($_POST['_age_from']) && isset($_POST['_age_to']) && !empty($_POST['_age_to']) ){
    $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "'. Secure($_POST['_age_from']) .'" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "'. Secure($_POST['_age_to']) . '"';
}else{
    if(isset( $_SESSION['_age_from'] ) && isset( $_SESSION['_age_to'] )) {
        $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "'. Secure($_SESSION['_age_from']) .'" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "'. Secure($_SESSION['_age_to']) . '"';
    }else{
        $where_and[] = 'DATEDIFF(CURDATE(), `birthday`)/365 >= "20" AND DATEDIFF(CURDATE(), `birthday`)/365 <= "55"';
    }
}
$qury_cuntry = '';
if( $u->show_me_to == '' ) {
    if (
        ( isset($_POST['_lat']) && !empty($_POST['_lat']) && isset($_POST['_lng']) && !empty($_POST['_lng']) )
        ||
        ( isset($_SESSION['_lat']) && !empty($_SESSION['_lat']) && isset($_SESSION['_lng']) && !empty($_SESSION['_lng']) )
    ) {
        $lat = 0;
        $lng = 0;
        $located = 7;
        if( isset( $_SESSION['_lat'] ) ) $lat = Secure($_SESSION['_lat']);
        if( isset( $_POST['_lat'] ) ) $lat = Secure($_POST['_lat']);

        if( isset( $_SESSION['_lng'] ) ) $lng = Secure($_SESSION['_lng']);
        if( isset( $_POST['_lng'] ) ) $lng = Secure($_POST['_lng']);

        if( isset( $_SESSION['_located'] ) ) $located = Secure($_SESSION['_located']);
        if( isset( $_POST['_located'] ) ) $located = Secure($_POST['_located']);

        $distance = 'ROUND( ( 6371 * acos(cos(radians(' . $lat . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $lng . ')) + sin(radians(' . $lat . ')) * sin(radians(`lat`)))) ,1) ';
        $where_and[] = $distance . ' <= ' . $located;
    }
}else{
    if( $country == true ) {
        $qury_cuntry = ' OR `country` = "' . $u->show_me_to . '"';
        $where_and[] = '`country` = "' . $u->show_me_to . '"';
    }
}
//******************* Looks Filters ************************//
if( isset($_POST['_height_from']) && !empty($_POST['_height_from']) && isset($_POST['_height_to']) && !empty($_POST['_height_to']) ){
    $where_or[] = '`height` BETWEEN "'. Secure($_POST['_height_from']) .'" AND "'. Secure($_POST['_height_to']) .'"';
}
if( isset($_POST['_body']) && !empty($_POST['_body']) ){
    if( strpos( Secure( $_POST['_body'] ), ',' ) === false ) {
        $where_or[] = '`body` = "'. Secure($_POST['_body']) . '"';
    }else{
        $where_or[] = '`body` IN ('. Secure($_POST['_body']) .')';
    }
}
//******************* Background Filter ********************//
if( isset($_POST['_language']) && !empty($_POST['_language']) ){
    $where_or[] = '`language` = "'. Secure($_POST['_language']) .'"';
}
if( isset($_POST['_ethnicity']) && !empty($_POST['_ethnicity']) ){
    if( strpos( Secure( $_POST['_ethnicity'] ), ',' ) === false ) {
        $where_or[] = '`ethnicity` = "'. Secure($_POST['_ethnicity']) . '"';
    }else{
        $where_or[] = '`ethnicity` IN ('. Secure($_POST['_ethnicity']) .')';
    }
}
if( isset($_POST['_religion']) && !empty($_POST['_religion']) ){
    if( strpos( Secure( $_POST['_religion'] ), ',' ) === false ) {
        $where_or[] = '`religion` = "'. Secure($_POST['_religion']) . '"';
    }else{
        $where_or[] = '`religion` IN ('. Secure($_POST['_religion']) .')';
    }
}
//******************* LifeStyle filter *********************//
if( isset($_POST['_relationship']) && !empty($_POST['_relationship']) ){
    if( strpos( Secure( $_POST['_relationship'] ), ',' ) === false ) {
        $where_or[] = '`relationship` = "'. Secure($_POST['_relationship']) .'"';
    }else{
        $where_or[] = '`relationship` IN ('. Secure($_POST['_relationship']) .')';
    }
}
if( isset($_POST['_smoke']) && !empty($_POST['_smoke']) ){
    if( strpos( Secure( $_POST['_smoke'] ), ',' ) === false ) {
        $where_or[] = '`smoke` = "'. Secure($_POST['_smoke']) . '"';
    }else{
        $where_or[] = '`smoke` IN ('. Secure($_POST['_smoke']) .')';
    }
}
if( isset($_POST['_drink']) && !empty($_POST['_drink']) ){
    if( strpos( Secure( $_POST['_drink'] ), ',' ) === false ) {
        $where_or[] = '`drink` = "'. Secure($_POST['_drink']) . '"';
    }else{
        $where_or[] = '`drink` IN ('. Secure($_POST['_drink']) .')';
    }
}
//******************* More Filter **************************//
if( isset($_POST['_interest']) && !empty($_POST['_interest']) ){
    $where_or[] = '`interest` like "%'. Secure($_POST['_interest']) .'%"';
}
if( isset($_POST['_education']) && !empty($_POST['_education']) ){
    if( strpos( Secure( $_POST['_education'] ), ',' ) === false ) {
        $where_or[] = '`education` = "'. Secure($_POST['_education']) . '"';
    }else{
        $where_or[] = '`education` IN ('. Secure($_POST['_education']) .')';
    }
}
if( isset($_POST['_pets']) && !empty($_POST['_pets']) ){
    if( strpos( Secure( $_POST['_pets'] ), ',' ) === false ) {
        $where_or[] = '`pets` = "'. Secure($_POST['_pets']) .'"';
    }else{
        $where_or[] = '`pets` IN ('. Secure($_POST['_pets']) .')';
    }
}
if( !empty($where_or) ){
    $where = $where . '('. implode($where_or, ' AND ') . ') ';
}
if( !empty($where_and) ){
    if( !empty($where_or) ) {
        $where = $where . ' AND (' . implode($where_and, ' AND ') . ')';
    }else{
        $where = $where . ' (' . implode($where_and, ' AND ') . ')';
    }
}

if( isset( $_REQUEST['access_token'] ) ) {
    $uid = GetUserFromSessionID(Secure($_REQUEST['access_token']));
    $u->id = $uid;
}

if( isset( $u->id ) ) {
    // to exclude blocked users
    $notin = ' OR `id` NOT IN (SELECT `block_userid` FROM `blocks` WHERE `user_id` = ' . $u->id . ') ';
    // to exclude liked and disliked users users
    $notin .= ' OR `id` NOT IN (SELECT `like_userid` FROM `likes` WHERE `user_id` = ' . $u->id . ') ';
    $notin .= ' OR `id` NOT IN (SELECT `user_id` FROM `likes` WHERE `like_userid` = ' . $u->id . ') ';
    $notin .= ' OR `id` <> "' . $u->id . '" ';
}

$custom_sql = [];
if(isset($_POST['custom_profile_data'])){
    $count = 100;
    for($i = 0 ; $i <= $count ; $i++ ){
        if(isset($_POST['fid_' . $i])){
            if(!empty($_POST['fid_' . $i])){
                $custom_sql[] = ' id IN (SELECT `user_id` FROM `userfields` WHERE `fid_' . $i .'` = "'.Secure($_POST['fid_' . $i]) . '") ';
            }
        }
    }
}

$custom_sql_text = '';
if(!empty($custom_sql)){
    $custom_sql_text .= ' AND ( ';
    $custom_sql_text .= implode(' OR ', $custom_sql);
    $custom_sql_text .= ' ) ';
}

if( $limit == 0 ){
    $limit = 20;
}
$orderBy = ' ORDER BY ';
$orderBy .= '`xlikes_created_at` DESC';
$orderBy .= ',`xvisits_created_at` DESC';
$orderBy .= ',`xmatches_created_at` DESC';
$orderBy .= ',`is_pro` DESC';
$query = $query . ' ' . $where . $notin . ') ' . $custom_sql_text . $qury_cuntry . $orderBy . ' LIMIT '.$limit.' OFFSET '.$offset.';';
return $query;

}

1 Ответ

0 голосов
/ 28 мая 2019

Зачем вам нужен отчетливый?Обычно пользователи уникальныgenders.

`gender` IN (4525,4526,1275,1277,1278,1279,1280,1281,1282,1283)

У вас есть 2 разницы в датах, а во втором нет компаратора.Также Datediff возвращает числовое значение, а не строку

DATEDIFF(CURDATE(), `birthday`)/365 >= "24"
DATEDIFF(CURDATE(), `birthday`)/365  "16" 

Теперь, если отсутствующий оператор в DATEDIFF не решает проблему.Идите прямо к БД, удалите все условия и начните добавлять их одно за другим, пока не найдете, какая из причин возвращает 0 строк.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...