These are the two tables I want to end up with:
tableA (I already have data in this table)
id | initials | name
1 | ER | Eric Robinsn
2 | DD | David Dobson
tableB (nothing in here yet)
id | tableA_id | nickname
1 | 1 | Rick
2 | 1 | Ricky
3 | 1 | Mr. Bossman
4 | 2 | Dave
5 | 2 | Davey
This is the JSON I have:
[
{
name: "Eric Robinson",
initials: "ER",
nicknames: ["Rick", "Ricky", "Mr. Bossman"]
},
{
name: "David Dobson",
initials: "DD",
nicknames: ["Dave", "Davey"]
}
]
Inserting into tableA
is very easy, you can do it like this with node-mysql:
vary connection = require("mysql");
var json = JSON.parse(require("./data.json"));
var sql = "INSERT INTO tableA(initials, name) VALUES ?";
connection.query(sql, json, callback);
But as a complete SQL noob how would I map the data into tableB
? After some researching I'm not sure if I can do this with something like the following:
INSERT INTO tableB (tableA_id, nickname)
SELECT id
FROM tableA
Or maybe I need to include a left join? The part that confuses me the most is how to include the tableA_id
part of the query into the statement. I've tried
INSERT INTO tableB (tableA_id, nickname)
SELECT id
FROM tableA
WHERE tableB.tableA_id = tableA.id //this is the part I don't get
This is just an abstracted example. Also, I'm using node-mysql so when I'm inserting into tableB
the re-mapped JSON looks looks like this:
[
{
initials: "ER", nickname: "Rick"
},
{
initials: "ER", nickname: "Ricky"
},
{
initials: "ER", nickname: "Mr. Bossman"
},
{
initials: "DD", nickname: "Dave"
},
{
initials: "DD", nickname: "Davey"
}
]