The data in the new MySQL table is the data of one or more tables (business scenario: create a relational table, copy the old table data to the new table)

question

A classmate asked me a question yesterday

I want to write a sql script to insert data in a loop. The data is the ab field
data in the A table in another table, and the ab field in the B table is added in a loop. That’s what it means

I asked him why he didn't write it in Java. He said it was for data maintenance, and he could only use SQL scripts. What is the relationship between the ab table? He replied:
no,Table B is a newly created relational table, Table B does not need to care about the relationship, it is now an empty table, and there is no data yet. Just put the data in table A in the past.

As soon as he said that table B is a relational table, I knew what he was going to do.

Solution


INSERT INTO b(字段1 ,字段2) SELECT 字段1,字段2 FROM a; 

delayed

He subconsciously added a value before the query , and the result was an error. I told him that this grammar has no values, and he was shocked. He
sent the chat record to my two disciples, and found that they didn’t know what to do after insert into Adding query statement directly does not need to add values , in fact, this is the principle of copying the old table data to the new table

understand

In fact, because I want to copy the data of a table to a new table before, I know a little about it.
I usually take it apart.Write the query statement first, and then add an insert into the field table to be added in front, In this way, there will never be any problems. You can add whatever you can find, and check what you want to add.
If you want to add a new relationship table in this way of writing , you can directly query the table first, and then add a new statement in front of it.
new table

-- 第二步,再在前面加上要新增到哪个表个什么字段,字段的数量和对应的值要对应
insert into student_score(`student_id`,`score_id`)
-- 第一步,先查询出来要新增的所有数据
select a.name,c.id from student a left join score c on a.classNo = c.id

run sql

success

Guess you like

Origin blog.csdn.net/weixin_46573158/article/details/126242516