- The ability to set variables in a statement with the := assignment operator:
- For e.g. (@total) to calculate the total in an example, you have to have the total column first because it must be calculated before the individual percentage calculations
- Session variables are set for the duration of the thread.
- In the vast majority of cases you'd use a programming language to do this sort of thing.
- MySQL variables can be useful when working on the MySQL command line.
- If no records are returned, the user variable will not be set for that statement.
- A user variable set in the field list cannot be used as a condition.
- The value of a variable is set with the SET statement or in a SELECT statement with :=
SELECT @test := 2; SELECT @test + 1; -- returns 3 SET @startdate='some_start_date', @enddate='some_end_date' SELECT @toremember:=COUNT(*) FROM membros; SELECT @numzero := COUNT(*) FROM table1 WHERE FIELD=0; SELECT @numdistinct := COUNT(DISTINCT FIELD) FROM table1 WHERE FIELD <> 0 ; SELECT @numzero @numdistinct;
- You can copy values retrieved by a SELECT into one or more variables:
USE hediard; SET @id = 0, @name = ''; SELECT id, name INTO @id, @name FROM table1 LIMIT 1; SELECT @id, @name;
A global variable is visible to all users, it allows to modify the configuration files settings during the session or definitely. So when changing them, it's necessary to precise this permanent or ephemera criteria, with respectively set global and set session. Example:
mysql> set @@global.max_connections = 1000; mysql> show global variables like 'wait_timeout'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | wait_timeout | 60 | +---------------+-------+ 1 row in set (0.00 sec) mysql> set @@session.wait_timeout=120;