这是我想要最终得到的两个表:
tableA (此表中已有数据)
id | initials | name
1 | ER | Eric Robinsn
2 | DD | David Dobson
tableB (此处尚无任何内容)
id | tableA_id | nickname
1 | 1 | Rick
2 | 1 | Ricky
3 | 1 | Mr. Bossman
4 | 2 | Dave
5 | 2 | Davey
这是我的JSON:
[
{
name: "Eric Robinson",
initials: "ER",
nicknames: ["Rick", "Ricky", "Mr. Bossman"]
},
{
name: "David Dobson",
initials: "DD",
nicknames: ["Dave", "Davey"]
}
]
插入tableA
非常简单,你可以使用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);
但作为一个完整的SQL菜鸟,我如何将数据映射到tableB
? After some researching我不确定我是否可以使用以下内容执行此操作:
INSERT INTO tableB (tableA_id, nickname)
SELECT id
FROM tableA
或者我可能需要包含左连接?最让我困惑的部分是如何将查询的tableA_id
部分包含在语句中。我试过了
INSERT INTO tableB (tableA_id, nickname)
SELECT id
FROM tableA
WHERE tableB.tableA_id = tableA.id //this is the part I don't get
这只是一个抽象的例子。另外,我使用node-mysql,所以当我插入tableB
时,重新映射的JSON看起来像这样:
[
{
initials: "ER", nickname: "Rick"
},
{
initials: "ER", nickname: "Ricky"
},
{
initials: "ER", nickname: "Mr. Bossman"
},
{
initials: "DD", nickname: "Dave"
},
{
initials: "DD", nickname: "Davey"
}
]