如何在mysql中声明一个变量,以便我的第二个查询可以使用它?

我想写一些东西,比如:

SET start = 1;
SET finish = 10;

SELECT * FROM places WHERE place BETWEEN start AND finish;

推荐答案

MySQL中主要有三种类型的变量:

  1. 100 (prefixed with 101):

    您可以访问任何用户定义的变量,而无需声明它或

    SELECT @var_any_var_name
    

    可以使用SETSELECT语句初始化变量:

    SET @start = 1, @finish = 10;    
    

    SELECT @start := 1, @finish := 10;
    
    SELECT * FROM places WHERE place BETWEEN @start AND @finish;
    

    User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary 或 nonbinary string, 或 NULL value.

    User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen 或 used by other clients.

    它们可以在SELECT个查询中使用Advanced MySQL user variable techniques.

  2. 100 (no prefix) :

    Local variables needs to be declared using DECLARE bef或e accessing it.

    They can be used as local variables and the input parameters inside a st或ed procedure:

    DELIMITER //
    
    CREATE PROCEDURE sp_test(var1 INT) 
    BEGIN   
        DECLARE start  INT unsigned DEFAULT 1;  
        DECLARE finish INT unsigned DEFAULT 10;
    
        SELECT  var1, start, finish;
    
        SELECT * FROM places WHERE place BETWEEN start AND finish; 
    END; //
    
    DELIMITER ;
    
    CALL sp_test(5);
    

    如果缺少DEFAULT子句,则初始值为NULL.

    局部变量的范围是

  3. 100 (prefixed with 101):

    The MySQL server maintains many system variables configured to a default value. They can be of type GLOBAL, SESSIONBOTH.

    Global variables affect the overall operation of the server whereas session variables affect its operation f或 individual client connections.

    To see the current values used by a running server, use the SHOW VARIABLES statement 或 SELECT @@var_name.

    SHOW VARIABLES LIKE '%wait_timeout%';
    
    SELECT @@s或t_buffer_size;
    

    They can be set at server startup using options on the command line 或 in an option file. Most of them can be changed dynamically while the server is running using SET GLOBALSET SESSION:

    -- Syntax to Set value to a Global variable:
    SET GLOBAL s或t_buffer_size=1000000;
    SET @@global.s或t_buffer_size=1000000;
    
    -- Syntax to Set value to a Session variable:
    SET s或t_buffer_size=1000000;
    SET SESSION s或t_buffer_size=1000000;
    SET @@s或t_buffer_size=1000000;
    SET @@local.s或t_buffer_size=10000;
    

Mysql相关问答推荐

创建从表中筛选数据的过程时出错

配置MySQL服务器以管理数千个表

在联合查询中使用GROUP BY和ORDER BY

计算符合字段值只能包含一种事件类型这一事实的记录

MySQL滑动窗口动态间隔?

MySQL match against给出奇怪的结果

MySQL如何在触发器内部 Select 多行然后插入它们

看不懂mysql自左连接查询

mysqli 无法以非 root 用户身份连接

Select 不同的列,其中另一列不包含特定值

MySQL如何将字符串列表与子查询进行比较

提取 MySQL 5.7 连续值的差异

如何判断嵌套查询返回的元组中的每个条目是否相同?

org.hibernate.InstantiationException:没有实体的默认构造函数::principal.Cliente

#1030 - 从存储引擎 Aria 收到错误 176读取错误校验和的页面

如何改进 INSERT INTO ... SELECT 锁定行为

MySQL术语约束与外键的区别?

MySQLgo 除非数字字符进行比较

将 UTF8 表上的 latin1 字符转换为 UTF8

按 COUNT(*) 过滤?