Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Insert Records from Multiple Tables to New Table

Tags:

mysql

I'm trying to populate a new table with records from 2 other tables.

period_states is new/empty

 period_states
   id
   period_id
   sla_id

periods - contains 15 records

periods
  id

slas - contains 84 records

slas
  id

I need to populate period_states with each existing sla_id having each exiting period_id. So, ultimately there should be 1260 records in period_states.

Any idea how to automate this? It would be a nightmare to populate manually...

Thank you in advance!!

like image 812
Katie M Avatar asked Oct 17 '11 21:10

Katie M


People also ask

How do I insert data from multiple tables into one table?

To insert records from multiple tables, use INSERT INTO SELECT statement. Here, we will insert records from 2 tables.

How do I combine data from multiple tables into one table in SQL?

Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other).

Is it possible to insert multiple records into table?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.


2 Answers

If the id column of period states is defined as AUTO_INCREMENT, then this should work:

INSERT INTO period_states (period_id, sla_id)
SELECT p.id AS period_id
     , s.id AS sla_id
  FROM periods p
 CROSS
  JOIN slas s

And here's an example of one way to supply a value for the id column:

INSERT INTO period_states (id, period_id, sla_id)
SELECT @myid := @myid + 1 AS id
     , p.id AS period_id
     , s.id AS sla_id
  FROM periods p
 CROSS
  JOIN slas s
 CROSS
  JOIN (SELECT @myid := 0) m
like image 105
spencer7593 Avatar answered Nov 15 '22 08:11

spencer7593


INSERT INTO period_states
(period_id, sla_id)
SELECT periods.id, slas.id
FROM periods
CROSS JOIN slas
like image 27
hair raisin Avatar answered Nov 15 '22 06:11

hair raisin