I have two tables (in two databases):
create table catalog_product_entity_text
(
value_id int auto_increment comment 'Value ID'
primary key,
attribute_id smallint unsigned default 0 not null comment 'Attribute ID',
store_id smallint unsigned default 0 not null comment 'Store ID',
entity_id int unsigned default 0 not null comment 'Entity ID',
value longtext null comment 'Value',
constraint CATALOG_PRODUCT_ENTITY_TEXT_ENTITY_ID_ATTRIBUTE_ID_STORE_ID
unique (entity_id, attribute_id, store_id),
constraint CATALOG_PRODUCT_ENTITY_TEXT_STORE_ID_STORE_STORE_ID
foreign key (store_id) references store (store_id)
on delete cascade,
constraint CAT_PRD_ENTT_TEXT_ATTR_ID_EAV_ATTR_ATTR_ID
foreign key (attribute_id) references eav_attribute (attribute_id)
on delete cascade,
constraint CAT_PRD_ENTT_TEXT_ENTT_ID_CAT_PRD_ENTT_ENTT_ID
foreign key (entity_id) references catalog_product_entity (entity_id)
on delete cascade
)
create table catalog_product_entity_varchar
(
value_id int auto_increment comment 'Value ID'
primary key,
attribute_id smallint unsigned default 0 not null comment 'Attribute ID',
store_id smallint unsigned default 0 not null comment 'Store ID',
entity_id int unsigned default 0 not null comment 'Entity ID',
value varchar(255) null comment 'Value',
constraint CATALOG_PRODUCT_ENTITY_VARCHAR_ENTITY_ID_ATTRIBUTE_ID_STORE_ID
unique (entity_id, attribute_id, store_id),
constraint CATALOG_PRODUCT_ENTITY_VARCHAR_STORE_ID_STORE_STORE_ID
foreign key (store_id) references store (store_id)
on delete cascade,
constraint CAT_PRD_ENTT_VCHR_ATTR_ID_EAV_ATTR_ATTR_ID
foreign key (attribute_id) references eav_attribute (attribute_id)
on delete cascade,
constraint CAT_PRD_ENTT_VCHR_ENTT_ID_CAT_PRD_ENTT_ENTT_ID
foreign key (entity_id) references catalog_product_entity (entity_id)
on delete cascade
)
My _text
table contains some data that I would like to transfer to the _varchar
table, but there's no correlation with the primary keys. The primary key is just auto increment.
Logically the tables are connected by the set (attribute_id, store_id, entity_id)
.
I would like to perform two actions:
Select all the values from
_text
table for specific attribute ids, e.g.select cpet.attribute_id, cpet.store_id, cpet.entity_id, cpet.value from catalog_product_entity_text cpet where cpet.attribute_id in (<myids>) and cpet.value is not null;
Now for each row in the above results I'd like to:
If there's corresponding
(attribute_id, store_id, entity_id)
in the_varchar
table, update that row.If there's no corresponding
(attribute_id, store_id, entity_id)
in the_varchar
table, add a new row with the data from the source row.
If I had a common primary key, I'd use REPLACE INTO
, but in this case I don't think it's suitable.
How can I build such a query? It doesn't need to be a single query.