ChatGPT解决这个技术问题 Extra ChatGPT

How to declare a variable in MySQL?

How to declare a variable in mysql, so that my second query can use it?

I would like to write something like:

SET start = 1;
SET finish = 10;

SELECT * FROM places WHERE place BETWEEN start AND finish;
Don't forget you may need "Allow User Variables=True".

M
Manos Nikolaidis

There are mainly three types of variables in MySQL:

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. SELECT @var_any_var_name You can initialize a variable using SET or SELECT statement: 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. 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. Local Variables (no prefix) : Local variables needs to be declared using DECLARE before accessing it. 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. The scope of a local variable is the BEGIN ... END block within which it is declared. Server System Variables (prefixed with @@): The MySQL server maintains many system variables configured to a default value. They can be of type GLOBAL, SESSION or BOTH. 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 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: -- 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;


Somehow = operator didn't work for me. It worked fine when I used := operator.
= operator only works in SET clause. For assigning value to a variable in SELECT query you can use := operator e.g. SELECT @start := 1
Can you please clarify what does this mean: "No need to declare User-Defined Session variables denoted with prefix @" ?
@billynoah I'm assuming it means that User-Defined Session variables (which begin with @) do not need an explicit declaration; you can just assign to them immediately as if they had already been declared.
And you can assign a variable with the result of a select statement like this: SET @subscriptionId = (select subscriptionId from User where emailAddress='ac@tmail.com');
b
bortunac

SET

SET @var_name = value;     /* or */     SET @var_name := 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);

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

in this case the result of select is not containing col2 values

Ex both methods used

-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations

...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col =  IFNULL( @NR, 0 ) + 1;
...

What is the difference between = and :=?
I guess that for mysql SELECT syntax is necessary to separate the meaning of = (comparation) from := (asign)
In certain cases, the values left in variables might NOT correspond to the last row returned. For example, SELECT DISTINCT IFNULL(@var:=Name,'unknown') FROM Customers ORDER BY <some non-indexed expression> LIMIT 10 appears to evaluate the variable assignments before the order-by is done, so that the returned value of @var might not even relate to any of the returned rows. The docs don't say under what conditions this can happen, though.
M
Mohammad Mahdi KouchakYazdi

Use set or select

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

example :

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

m
mohammadAli

Different types of variable:

local variables (which are not prefixed by @) are strongly typed and scoped to the stored program block in which they are declared. Note that, as documented under DECLARE Syntax:

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

User variables (which are prefixed by @) are loosely typed and scoped to the session. Note that they neither need nor can be declared—just use them directly.

Therefore, if you are defining a stored program and actually do want a "local variable", you will need to drop the @ character and ensure that your DECLARE statement is at the start of your program block. Otherwise, to use a "user variable", drop the DECLARE statement.

Furthermore, you will either need to surround your query in parentheses in order to execute it as a subquery:

SET @countTotal = (SELECT COUNT(*) FROM nGrams);

Or else, you could use SELECT ... INTO:

SELECT COUNT(*) INTO @countTotal FROM nGrams;


y
yaya

Declare: SET @a = 1;

Usage: INSERT INTO `t` (`c`) VALUES (@a);


t for table and c for column?
@carloswm85 yes
I
Imran Javed

For any person using @variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. Otherwise it can use old value for same session.

Set @Ids = '';

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

H
Hari Lakkakula

SET Value

 declare @Regione int;   
 set @Regione=(select  id from users
 where id=1) ;
 select @Regione ;