MySQL CONCAT表过滤语法

时间:2015-01-15 17:12:55

标签: mysql sql syntax syntax-error concatenation

我收到错误" 错误代码:1064。您的SQL语法错误;检查与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便在附近使用' ORDER BY p。promo_code ASC'第1行"在我的订单上的条款和我不知道为什么,当我取消查询查询它似乎工作正常。

我错过了什么吗?这是我的代码:

    SET _select = CONCAT( "SELECT p.`promo_code` AS code, p.`name` AS username, p.`company` AS company " );
    SET _select = CONCAT( _select, " FROM `promos` AS p" );

    SET _where = CONCAT( " WHERE 1 = 1");

    IF _promoCode IS NOT NULL THEN
        SET _where = CONCAT( _where, " AND ( p.`promo_code` LIKE '%", _promoCode, "%'" );
    END IF;
    IF _companyName IS NOT NULL THEN
        SET _where = CONCAT( _where, " AND ( p.`company` LIKE '%", _companyName, "%'" );
    END IF;
    IF _userName IS NOT NULL THEN
        SET _where = CONCAT( _where, " AND ( p.`name` LIKE '%", _userName, "%'" );
    END IF;

    -- SET _where_total = _where;

    #SORT option protocols, 1 is promocode, 2 is company, 3 is name; Second number is ASC/DESC
    IF _sortOrder IS NOT NULL THEN
        CASE _sortOrder
            WHEN 10 THEN
                SET _where = CONCAT( _where, " ORDER BY p.`promo_code` ASC" );
            WHEN 11 THEN
                SET _where = CONCAT( _where, " ORDER BY p.`promo_code` DESC" );
            WHEN 20 THEN
                SET _where = CONCAT( _where, " ORDER BY p.`company` ASC" );
            WHEN 21 THEN
                SET _where = CONCAT( _where, " ORDER BY p.`company` DESC" );
            WHEN 30 THEN
                SET _where = CONCAT( _where, " ORDER BY p.`name` ASC" );
            WHEN 31 THEN
                SET _where = CONCAT( _where, " ORDER BY p.`name` DESC" );
            ELSE
                SELECT "Please use valid sort protocol";
        END CASE;
    END IF;

    /*SET _where = CONCAT( _where, " LIMIT ", _start, ", ", _records );*/

    SET @query = CONCAT( _select, _where );

    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    SET _select_total = "SELECT COUNT( p.`promo_code` ) AS total_matching_promos ";
    SET _select_total = CONCAT( _select_total, " FROM `promos` AS p " );

    SET @query = CONCAT( _select_total, _where_total );

    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

1 个答案:

答案 0 :(得分:0)

发现了这个问题。

条件WHERE子句中有一些左括号:

IF _promoCode IS NOT NULL THEN
    SET _where = CONCAT( _where, " AND **(** p.`promo_code` LIKE '%", _promoCode, "%'" );
END IF;
IF _companyName IS NOT NULL THEN
    SET _where = CONCAT( _where, " AND **(** p.`company` LIKE '%", _companyName, "%'" );
END IF;
IF _userName IS NOT NULL THEN
    SET _where = CONCAT( _where, " AND **(** p.`name` LIKE '%", _userName, "%'" );
END IF;

已删除并移动了SET _where_total = _where; 就在SET @query = CONCAT( _select, _where );

之前

不要盲目复制粘贴代码:P