- MySQL 8.0
- Joomla 4.4.3
- HikaShop 5.0.3
Hi, I'm developing an eCommerce website and I need to run an SQL command that update the category of all products that have a category beginning with 'HP '. There is a table PRODUCT with all products, a table CATEGORY with all categories and a table PRODUCT_CATEGORY that links product_id and category_id
The tables link are:
PRODUCT
product_id
icecat_category
PRODUCT_CATEGORY
category_id
product_id
CATEGORY
category_id
category_name
The Update i would like to perform is: search all the PRODUCT.product_id that have a CATEGORY.category_name LIKE 'HP %' and for this items modify the PRODUCT_CATEGORY.category_id and SET it to the CATEGORY.category_id WHERE CATEGORY.category_name = PRODUCT.icecat_category
I am sure it is more difficoult to explain rather to create the right SQL statement, i hope i'm been clear enough. Thank you very much Eiasu
Answers
To achieve the desired update in MySQL, you can use a combination of UPDATE
and JOIN
statements to update the PRODUCT_CATEGORY
table based on conditions involving the PRODUCT
and CATEGORY
tables. Here's the SQL statement to accomplish this task:
UPDATE PRODUCT_CATEGORY AS pc
JOIN PRODUCT AS p ON pc.product_id = p.product_id
JOIN CATEGORY AS c ON p.icecat_category = c.category_name
SET pc.category_id = c.category_id
WHERE c.category_name LIKE 'HP %';
Let's break down this SQL statement:
-
UPDATE PRODUCT_CATEGORY AS pc
: Specifies the table to update and assigns an aliaspc
for it. -
JOIN PRODUCT AS p ON pc.product_id = p.product_id
: Joins thePRODUCT_CATEGORY
table with thePRODUCT
table based on theproduct_id
column to get product details. -
JOIN CATEGORY AS c ON p.icecat_category = c.category_name
: Joins thePRODUCT
table with theCATEGORY
table based on theicecat_category
column to get the category details. -
SET pc.category_id = c.category_id
: Sets thecategory_id
column in thePRODUCT_CATEGORY
table to thecategory_id
column in theCATEGORY
table. -
WHERE c.category_name LIKE 'HP %'
: Filters the rows where the category name starts with 'HP '.
This SQL statement will update the PRODUCT_CATEGORY
table for all products whose icecat category matches a category name starting with 'HP '.