-- Duplicate the structure of a table:
CREATE TABLE artist_2 LIKE artist; -- create table 'artist_2', with indentical structure to table 'artist', no data
-- Create a table and copy some data:
CREATE TABLE artist_2 SELECT * FROM artist; -- completely identical table now
-- Create a table with data from multiple other tables:
-- example - 'report' table that contains names of artists and their albums:
CREATE TABLE report (artist_name CHAR(128), album_name CHAR(128)) -- not duplicating structure
SELECT artist_name, album_name FROM artist INNER JOIN album -- data copied from artist and album
USING (artist_id);
\!h NOTE: a query like this won't copy indexes(keys), to do so:
-- use LIKE to create an empty table with the indexes, then copy data using INSERT with SELECT.
-- or:
-- CREATE TABLE with a SELECT statement, then add indexes using ALTER TABLE.
-- or:
-- Use the UNIQUE(or PRIMARY KEY, or KEY) keyword, in combination with the CREATE TABLE and SELECT stament:
CREATE TABLE artist_2 (UNIQUE(artist_id)) -- PRI key is now artist_id
SELECT * FROM artist;
\!h Anything you can do in a regular CREATE TABLE statement, you can do in this variant
-- this includes DEFAULT, NULL, PRIMARY KEY settings etc:
CREATE TABLE artist_3
(artist_id SMALLINT(5), NOT NULL AUTO_INCREMENT,
artist_name CHAR(128) NOT NULL DEFAULT "New Order",
PRIMARY KEY (artist_id), KEY(artist_name))
SELECT * FROM artist;