SQL左连接插入不起作用

时间:2014-12-08 18:54:40

标签: mysql sql insert phpmyadmin left-join

我想从entity_id表中的每一行获取catalog_product_entity值,并从store_id表中的每一行获取每个catalog_product_entity_int值,其中{第一个表的{1}}等于第二个表的entity_id

此SQL插入语句有什么问题:

entity_id

MySQL说:

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;

2 个答案:

答案 0 :(得分: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中的插入选择语句。

答案 1 :(得分:1)

您不需要在select statment上的insert上指定fileds。

您的查询应该是

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语句中添加插入目标表所需的所有字段