如何在MySQL中声明变量?

本文翻译自:How to declare a variable in MySQL?

How to declare a variable in mysql, so that my second query can use it? 如何在mysql中声明变量,以便第二个查询可以使用它?

I would like to write something like: 我想写一些像:

SET start = 1;
SET finish = 10;

SELECT * FROM places WHERE place BETWEEN start AND finish;

#1楼

参考:https://stackoom.com/question/nJxF/如何在MySQL中声明变量


#2楼

There are mainly three types of variables in MySQL: MySQL中主要有三种类型的变量:

  1. User-defined variables (prefixed with @ ): 用户定义的变量 (以@开头):

    You can access any user-defined variable without declaring it or initializing it. 您可以访问任何用户定义的变量,而无需对其进行声明或初始化。 If you refer to a variable that has not been initialized, it has a value of NULL and a type of string. 如果引用的变量尚未初始化,则其值为NULL和字符串类型。

     SELECT @var_any_var_name 

    You can initialize a variable using SET or SELECT statement: 您可以使用SETSELECT语句初始化变量:

     SET @start = 1, @finish = 10; 

    or 要么

     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 or nonbinary string, or NULL value. 可以从一组有限的数据类型中为用户变量分配一个值:整数,十进制,浮点数,二进制或非二进制字符串或NULL值。

    User-defined variables are session-specific. 用户定义的变量是特定于会话的。 That is, a user variable defined by one client cannot be seen or used by other clients. 即,一个客户端定义的用户变量不能被其他客户端看到或使用。

    They can be used in SELECT queries using Advanced MySQL user variable techniques . 可以使用高级MySQL用户变量技术SELECT查询中使用它们。

  2. Local Variables (no prefix) : 局部变量 (无前缀):

    Local variables needs to be declared using DECLARE before accessing it. 访问之前,需要使用DECLARE声明局部变量。

    They can be used as local variables and the input parameters inside a stored 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); 

    If the DEFAULT clause is missing, the initial value is NULL . 如果缺少DEFAULT子句,则初始值为NULL

    The scope of a local variable is the BEGIN ... END block within which it is declared. 局部变量的范围是在其内声明的BEGIN ... END块。

  3. Server System Variables (prefixed with @@ ): 服务器系统变量 (以@@前缀):

    The MySQL server maintains many system variables configured to a default value. MySQL服务器维护许多配置为默认值的系统变量 They can be of type GLOBAL , SESSION or BOTH . 它们的类型可以是GLOBALSESSIONBOTH

    Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections. 全局变量影响服务器的整体操作,而会话变量影响单个客户端连接的服务器操作。

    To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT @@var_name . 要查看正在运行的服务器使用的当前值,请使用SHOW VARIABLES语句或SELECT @@var_name

     SHOW VARIABLES LIKE '%wait_timeout%'; SELECT @@sort_buffer_size; 

    They can be set at server startup using options on the command line or in an option file. 可以在服务器启动时使用命令行或选项文件中的选项来设置它们。 Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION : 当服务器使用SET GLOBALSET SESSION运行时,大多数可以动态更改:

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

#3楼

Use set or select 使用设置选择

SET @counter := 100;
SELECT @variable_name := value;

example : 例如:

SELECT @price := MAX(product.price)
FROM product 

#4楼

SET

SET @var_name = value 

OR 要么

SET @var := value

both operators = and := are accepted 运算符=:=都被接受


SELECT 选择

SELECT col1, @var_name := col2 from tb_name WHERE "conditon";

if multiple record sets found only the last value in col2 is keep (override); 如果发现多个记录集,则仅col2中的最后一个值是keep(覆盖);

SELECT col1, col2 INTO @var_name, col3 FROM .....

in this case the result of select is not containing col2 values 在这种情况下,select的结果不包含col2值


#5楼

For any person using @variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. 对于在concat_ws函数中使用@variable来获取串联值的任何人,请不要忘记使用空值重新初始化它。 Otherwise it can use old value for same session. 否则,它可以将旧值用于同一会话。

Set @Ids = '';

select 
  @Ids := concat_ws(',',@Ids,tbl.Id),
  tbl.Col1,
  ...
from mytable tbl;

#6楼

SET Value 设定值

 declare Regione int;   
 set Regione=(select  id from users
 where id=1) ;
 select Regione ;
MySQL触发器,你可以使用DECLARE语句来声明变量变量可以用于存储和操作数据,以及进行条件判断和循环等操作。 以下是一个示例,展示了如何在MySQL触发器声明和使用变量: ```sql DELIMITER // CREATE TRIGGER update_total_orders AFTER INSERT ON orders FOR EACH ROW BEGIN DECLARE customer_name VARCHAR(50); DECLARE order_count INT; -- 获取插入行的客户名 SELECT name INTO customer_name FROM customers WHERE id = NEW.customer_id; -- 获取客户的订单总数 SELECT total_orders INTO order_count FROM customers WHERE id = NEW.customer_id; -- 更新客户的订单总数 SET order_count = order_count + 1; -- 输出调试信息 SELECT CONCAT('Updating total orders for customer ', customer_name, ' to ', order_count) AS message; -- 更新"customers"表对应客户的订单总数 UPDATE customers SET total_orders = order_count WHERE id = NEW.customer_id; END; // DELIMITER ; ``` 在这个示例,我们声明了两个变量:customer_name和order_count。首先,我们使用SELECT INTO语句将插入行的客户名存储到customer_name变量。然后,我们使用同样的方法将该客户的订单总数存储到order_count变量。 接下来,我们通过SET语句将order_count增加1,以更新订单总数。在这之后,我们使用SELECT语句输出一条调试信息,显示更新后的订单总数。 最后,我们使用UPDATE语句更新"customers"表对应客户的订单总数,将变量order_count的值赋给total_orders列。 注意,在触发器使用变量时,需要使用DECLARE语句进行声明,并使用SET语句进行赋值和操作。 希望这个示例能帮助你理解在MySQL触发器如何声明和使用变量。如有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值