【问题标题】:How do i insert multiple varying values from a column in one table to another table with the corresponding foreign key referenced?如何将多个不同值从一个表中的列插入到另一个表并引用相应的外键?
【发布时间】:2019-11-22 19:02:22
【问题描述】:

主列表

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| Brand | varchar(255) | YES  |     | NULL    |                |
| Name  | varchar(255) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

品牌

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| BRAND_ID | int(11)      | NO   | PRI | NULL    | auto_increment |
| Brand    | varchar(255) | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

产品

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment | 
| Name     | varchar(255) | NO   |     | NULL    |                |
| BRAND_ID | int(11)      | NO   | MUL | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

您好,我对 MySQL 和数据库比较陌生,我想寻求一种方法来将我的数据从一个表填充到另一个表。

场景

products(Brand ID) 上创建引用brands(BRAND_ID) 的外键后,我需要将masterlist 表中的值插入products。具体来说,Name 列下的值是唯一的,但与brands 表中的BRAND_ID 键相关联;在products 表中提供引用值。

我当前的代码

INSERT INTO products(Name, BRAND_ID)
VALUES
  ((SELECT Name from masterlist WHERE id = 85), 5),
  ((SELECT Name from masterlist WHERE id = 86), 5)

这是我正在使用的当前解决方案的一个示例;我知道这是我想要实现的最糟糕的解决方案。有什么更有效的方法来解决这个问题?

【问题讨论】:

    标签: mysql database phpmyadmin


    【解决方案1】:

    您是否在寻找 insert ... select 语法,像这样?

    insert into products(name, brand_id)
    select name, 5 from masterlist where id in (85, 86)
    

    【讨论】:

    • 您好,感谢您帮助我。我已经尝试了代码,但它返回了 #1054 - 'where 子句'中的未知列 'id'
    • @biendilales:您的架构描述了表masterlist 中的列id。表中有这样的列吗?
    猜你喜欢
    • 2020-12-11
    • 2023-03-17
    • 2019-01-06
    • 2019-09-29
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多