DavidSzczesniak
2/9/2018 - 5:42 PM

Inserting Data using Queries

This can be done using SELECT and INSERT together in one statement.

\!h Example - auto_increment 'shuffle playlist' table:
-- the table
CREATE TABLE shuffle (
artist_id SMALLINT(5) NOT NULL DEFAULT 0, 
album_id SMALLINT(4) NOT NULL DEFAULT 0,
track_id SMALLINT(3) NOT NULL DEFAULT 0, 
sequence_id SMALLINT(3) AUTO_INCREMENT NOT NULL, -- shuffle feature
PRIMARY KEY (sequence_id));

-- the insert:
-- column names optional here. If omitted, they would be assumed in the same order they are in a SHOW CREATE TABLE or DESCRIBE TABLE statement.
INSERT INTO shuffle (artist_id, album_id, track_id) -- column names 
SELECT artist_id, album_id, track_id FROM -- copy IDs from the track table
track ORDER BY RAND() LIMIT 10; -- insert randomised tracks(pseudorandom order) from the 'track' table, with a limit of 10
-- note: RAND() returns a pseudorandom number in the range 0 to 1.

\!h Further, this can also be used to query data from one database to another.
-- Example, to the the artist table from the music db, use 'music.artist'.