Sunday, October 29, 2017

MySQL user variables

Set a variable @artist to equal a value from the artist table:
SELECT @artist:=artist_name from artist where artist_id = 1;

Reveal the variable contents:
SELECT @artist;

Define a variable and value:
SET @fruit := 'banana';
SELECT @fruit;

This reveals the name of the track that was played most recently.
It shows how you can define a variable and then use it in a later query:
SELECT MAX(played) FROM played;

SELECT @recent := MAX(played) FROM played;

SELECT track_name FROM track INNER JOIN played
USING (artist_id, album_id, track_id)
WHERE played = @recent;

[Summarized from Learning MySQL]