MYSQL - 准备stmt并执行stmt并添加WHERE和LIKE

时间:2012-07-24 13:21:25

标签: mysql

我正在尝试构建下一个存储过程,但它无法正常工作。

PREPARE STMT FROM 'SELECT a, b, c, d, e FROM TABLE_1 WHERE (`a` like `%?%` OR `b` like `%?%` OR `c` like `%?%` OR `d` like `%?%` OR `e` like `%?%`) LIMIT ?, ?';
EXECUTE STMT USING @search, @skip, @rows;

基本上,我正在尝试在其中一列中搜索一个字符串,并返回包含适合列的行。 请帮我解决,因为我收到了下一个错误:

Unknown column '%?%' in 'where clause'

3 个答案:

答案 0 :(得分:0)

这是因为多少?应该等于USING子句后的参数数量。你也给错了报价?而不是"?"尝试:

PREPARE STMT FROM 'SELECT a, b, c, d, e FROM TABLE_1 WHERE (`a` like "%?%" OR `b` like "%?%" OR `c` like "%?%" OR `d` like "%?%" OR `e` like "%?%") LIMIT ?, ?';

EXECUTE STMT USING @search, @search, @search, @search, @search, @skip, @rows;

或尝试

SET @query1 = CONCAT('
    SELECT SQL_CALC_FOUND_ROWS a, b, c, d, e
    FROM TABLE_1
    WHERE (`a` like "%',@search,'%" OR
        `b` like "%',@search,'%" OR
        `c` like "%',@search,'%" OR
        `d` like "%',@search,'%" OR
        `e` like "%',@search,'%")
    LIMIT ',@skip,', ',@rows,'');

    PREPARE stmt FROM @query1; 
    EXECUTE stmt; 
    SELECT FOUND_ROWS() AS total_rows;
    DEALLOCATE PREPARE stmt;

答案 1 :(得分:0)

mysql上的给定示例似乎显示了问号的数量 应该与参数计数相似吗?

http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html

我错了吗?

在您的情况下,这意味着七个问号以及七个参数。

一切顺利

答案 2 :(得分:0)

试试这个......

PREPARE STMT FROM 'SELECT a, b, c, d, e FROM TABLE_1 WHERE (`a` like "%?%" OR `b` like "%?%" OR `c` like "%?%" OR `d` like "%?%" OR `e` like "%?%") LIMIT ?, ?';

EXECUTE STMT USING @search, @search, @search, @search, @search, @skip, @rows;

注意

变量数量应该等于我们拥有的问号数量。

你有7个问号,只有3个变量。所以错误来自第4 ?