我收到错误“错误代码:1064。您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,了解在“ORDER BY p.”附近使用的正确语法。promo_code
ASC' at line 1” 在我的 order by 子句中,我不确定为什么,当我取消 CONCAT 查询时,它似乎工作正常。
我错过了什么吗?这是我的代码:
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;
最佳答案
发现问题。
条件 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
关于MySQL CONCAT 表过滤语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27969092/