使用between,date_add和getdate之间的年龄搜索语法中的sql错误

时间:2015-10-15 17:34:32

标签: mysql sql

我在搜索结果中进行了年龄过滤,但我的语法错误:

这是我的php for sql;

    //the age advance search
    switch (Request::get('member_age')):
        case '18-25':
            $age = " AND user_birthdate BETWEEN Date_Add(yy, -26, GetDate()) And Date_Add(yy, -18, GetDate()) ";
            break;
        case '26-35':
            $age = "AND user_birthdate BETWEEN Date_Add(yy, -35, GetDate()) And Date_Add(yy, -26, GetDate())";
            break;
        case '36-45':
            $age = "AND user_birthdate BETWEEN Date_Add(yy, -45, GetDate()) And Date_Add(yy, -36, GetDate())";
            break;
        case '46-55':
            $age = "AND user_birthdate BETWEEN Date_Add(yy, -55, GetDate()) And Date_Add(yy, -46, GetDate())";
            break;
        case '56-65':
            $age = "AND user_birthdate BETWEEN Between Date_Add(yy, -65, GetDate()) And Date_Add(yy, -56, GetDate())";
            break;
        case '65+':
            $age = "AND user_birthdate BETWEEN Between Date_Add(yy, -999999, GetDate()) And Date_Add(yy, -55, GetDate())";
            break;
        default:
            $age = "";
    endswitch;

我的sql:

    $search_people_sql = "SELECT *
                          FROM users
                          LEFT JOIN friends
                            ON users.user_id  = friends.friends_friend  
                          LEFT JOIN friend_request 
                            ON users.user_id  = friend_request.friend_request_to 
                            OR users.user_id  = friend_request.friend_request_from  
                          LEFT JOIN user_personal_information
                            ON user_personal_information.user_personal_information_user = friends.friends_friend
                          WHERE CONCAT_WS(' ', user_personal_information.user_firstname, user_personal_information.user_surname) LIKE ?
                          AND user_enabled = 1
                          AND user_id      != ?
                          ".$age." 

但是收到此错误

  

警告:PDOStatement :: execute():SQLSTATE [42000]:语法错误或   访问冲突:1064您的SQL语法有错误;检查   手册,对应右边的MySQL服务器版本   在'-26,GetDate())和Date_Add(yy,-18,GetDate())'

附近使用的语法

2 个答案:

答案 0 :(得分:1)

对不起,这不是答案,只是大评论。

你有:

AND user_birthdate BETWEEN Date_Add(yy, -26, GetDate()) And Date_Add(yy, -18, GetDate())";

这种语法错了:

  1. mysql中没有GetDate()函数

  2. 根据{{​​3}},
  3. DATE_ADD的语法不同:

  4. 如果使用mysql,这部分看起来像:

    AND user_birthdate BETWEEN Date_Add(NOW(), INTERVAL -26 YEAR) And Date_Add(NOW(), INTERVAL -18 YEAR)";
    

    所以你必须改变你的所有字符串来纠正mysql语法。

答案 1 :(得分:-1)

尝试使用Date_Add(yy,-26,Now())

您可能需要CAST日期

CAST(Date_Add(yy,-26,Now()))AS DATE