【问题标题】:SQL Left Join Insert not workingSQL左连接插入不起作用
【发布时间】:2014-12-08 18:54:39
【问题描述】:

我想从catalog_product_entity 表中的每一行获取entity_id 值,并从catalog_product_entity_int 表中的每一行获取每个store_id 值,其中第一个表的entity_id 相等到第二张表的entity_id

这个 SQL 插入语句有什么问题:

INSERT INTO `catalog_product_entity_varchar` ("","4","231",i.store_id,p.entity_id,"D")
SELECT p.entity_id, i.store_id
                FROM catalog_product_entity p
                LEFT JOIN catalog_product_entity_int i 
                ON i.entity_id = p.entity_id;

MySQL 说:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"","4","231",i.store_id,p.entity_id,"D")
SELECT p.entity_id, i.store_id
                FR' at line 1 

【问题讨论】:

  • 应该是这样的。 INSERT INTO catalog_product_entity_varchar SELECT '',4, 231, i.store_id, p.entity_id, 'D' FROM catalog_product_entity p LEFT JOIN catalog_product_entity_int i ON i.entity_id = p.entity_id;

标签: mysql sql insert phpmyadmin left-join


【解决方案1】:

您混淆了两种类型的插入语句。

如果您尝试从一个表中选择要插入的值,它将如下所示:

INSERT INTO `catalog_product_entity_varchar` 
     (field1, field2, field3, field4, field5, field6)
SELECT "","4","231",i.store_id,p.entity_id,"D"
                FROM catalog_product_entity p
                LEFT JOIN catalog_product_entity_int i 
                ON i.entity_id = p.entity_id;

将值的硬编码部分添加到 select 语句中,并在插入时指定它们要进入的字段。

阅读mysql doc page 中的插入选择语句。

【讨论】:

    【解决方案2】:

    您不需要在 select 语句的插入中指定文件。

    你的查询应该类似于

    INSERT INTO `catalog_product_entity_varchar` 
    SELECT p.entity_id, i.store_id  --ADD MORE FIELDS HERE TO MATCH YOUR TARGET TABLE SCHEMA
                    FROM catalog_product_entity p
                    LEFT JOIN catalog_product_entity_int i 
                    ON i.entity_id = p.entity_id;
    

    请注意,我删除了 ("","4","231",i.store_id,p.entity_id,"D")

    您需要在SELECT 语句中添加插入目标表所需的所有字段

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      相关资源
      最近更新 更多