简体   繁体   English

如何根据另外两个表的连接插入值 (MySQL)

[英]How to insert values based on a join of two other tables (MySQL)

I'm sorry if this has been asked before, I've gone through tens of questions and none of them solved my issue.很抱歉,如果之前有人问过这个问题,我已经回答了数十个问题,但没有一个能解决我的问题。

Here is an example of my Data.table: Table1这是我的 Data.table 的示例: 表 1

program程序 category类别
Acrobat杂技演员 PDF PDF
Photoshop Photoshop graphics图形
After Ef在 Ef 之后 video视频

So here, we have the program Acrobat in the category PDF, Photoshop in the category graphics, After Effects in the category video.所以在这里,我们在类别 PDF 中有程序 Acrobat,在图形类别中有 Photoshop,在视频类别中有 After Effects。 I have a table for categories and a table for programs:我有一个类别表和一个程序表:

CREATE TABLE categories
(
cat_id int AUTO_INCREMENT,
category varchar(255),
PRIMARY KEY (cat_id)
);
  CREATE TABLE programs
(
    program_id int AUTO_INCREMENT,
    program varchar(255),
    cat_id int,
    PRIMARY KEY (program_id),
    FOREIGN KEY (cat_id) REFERENCES categories(cat_id)
);

ALTER TABLE programs AUTO_INCREMENT=100;

My problem is, I need to link the cat_id from the programs table to the program column in Table 1. Essentially, I need:我的问题是,我需要将程序表中的 cat_id 链接到表 1 中的程序列。本质上,我需要:

Table1: program -> category表 1:程序 -> 类别

categories: category -> cat_id类别:类别 -> cat_id

programs: program -> cat_id程序:程序 -> cat_id

What sort of join (or other operation) do I need to do in order to complete the programs table?为了完成程序表,我需要做什么样的连接(或其他操作)? Right now, the cat_id column is all "null".现在,cat_id 列全部为“null”。

I've tried linking the categories table to Table1 (hoping it would simplify the join with the programs table) and all sorts of combinations of INSERT INTO programs... INNER JOIN on... but I'm either getting "ambiguous" errors or other errors.我已经尝试将类别表链接到 Table1(希望它会简化与程序表的连接)以及 INSERT INTO 程序的各种组合......INNER JOIN on......但我要么得到“模棱两可”的错误或其他错误。 Nothing has worked.没有任何效果。

Is that what you want:那是你要的吗:

You can copy only some columns from one table into another table:您只能将一个表中的某些列复制到另一个表中:

insert into programs(program, cat_id)
select t.program, c.cat_id
from table1 t
inner join categories c on c.category = t.category

Demo here演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM