使用查询来确定变量的值(MySQL)

时间:2016-02-26 13:49:58

标签: mysql variables

我试图将一个count的值放入一个变量中,以便与另一个查询一起使用。

但是它不起作用,它说:

  

[Err] 1064 - 您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的'SELECT COUNT(columnname)FROM field WHERE tabid = 4'附近使用正确的语法

我使用的查询是:

SET @_count = SELECT COUNT(columnname) FROM field WHERE tabid = 4;

3 个答案:

答案 0 :(得分:1)

您需要在括号中包装SQL Select Query。

SET @_count = (SELECT COUNT(columnname) FROM field WHERE tabid = 4);

答案 1 :(得分:0)

SELECT COUNT(*) into @_count from  field WHERE tabid = 4; 

select @_count;   

结果

答案 2 :(得分:0)

做到了,这就是:

    /**
     * Query to find and select all the fields with a specific name on any tab id
     */

    -- Prepare the variables for the query
    SET @_tabid = 4; -- Replace with your tab id
    SET @_lowerletter = "%%"; -- Replace with your lower case search
    SET @_upperletter = "%%"; -- Replace with your upper case search
    SET @_upperlimit = (SELECT COUNT(columnname) FROM field WHERE tabid = @_tabid);
    SET @_lowerlimit = 0; -- Set your lower limit
    SET @_query = "SELECT * FROM field 
                                 WHERE tabid = ?
                                 AND (
                                    (columnname LIKE ? OR columnname LIKE ?) OR 
                                    (fieldname LIKE ? OR fieldname LIKE ?) OR 
                                    (fieldlabel LIKE ? OR fieldlabel LIKE ?)
                                 )
                                 ORDER BY tabid, fieldid ASC
                                 LIMIT ?, ?;";
    -- //Prepare

    -- Prepare and execute query
    PREPARE stmt FROM @_query;
            EXECUTE stmt USING 
                @_tabid,
                @_lowerletter, @_upperletter, -- Upper and lower search terms 
                @_lowerletter, @_upperletter, -- Upper and lower search terms 
                @_lowerletter, @_upperletter, -- Upper and lower search terms 
                @_lowerlimit, @_upperlimit; -- Upper and lower limits 
    DEALLOCATE PREPARE stmt;
    -- // Execute