DavidSzczesniak
2/8/2018 - 5:08 PM

User Variables

Allows to store the result of a query and use it later.

\!h Variable names:
-- case-insensitive from v5+
-- alphanumeric strings
-- can include the period, underscore and dollar signs

\!h Simple example - find the name of an artist and save the result in a user variable
SELECT @artist:=artist_name FROM artist WHERE artist_id = 1;
+----------------------+
| @artist:=artist_name | -- user variable with the name artist,
+----------------------+ -- denoted by the @ symbol and assigned with :=
| New Order            |
+----------------------+

\!h To print the contents of a user variable:
SELECT @artist;
+-----------+
| @artist   |
+-----------+
| New Order |
+-----------+

\!h Explicitly set a variable using SET:
SET @counter:= 0; -- initialize a counter to 0

\!h Multiple assignments on one line:
SET @counter:= 0, @age:= 23;

\!h Example 2 - Save something for later:
SELECT @recent:= MAX(played) FROM played; -- user variable that saves most recent played time
+-----------------------+
| @recent:= MAX(played) |
+-----------------------+
| 2006-08-15 14:33:57   |
+-----------------------+
-- separate query using the user variable - name of the song played most recently
SELECT track_name FROM track INNER JOIN played
USING (artist_id, album_id, track_id)
WHERE played = @recent;
+------------+
| track_name |  
+------------+
| New Blues  |
+------------+
-- saves cutting and pasting + helps avoid typos