We have a table "url_rewrite" in our Magento 2 store and we need to copy a lot of values inside this table.
We have a column "store_id", that contains values from 1 until 4. Another column with "target_path" and the last column with "request_path".
Now we need to replace the "request_path" of all rows that contains the value "4" inside the "store_id" and where the "target_path" is the exact same of rows with "store_id" 2 and 4, with the value of rows with "store_id" 2.
So from the screenshot the row with "store_id" 4 should get the "request_path" value like "laptops/apple-macbook/apple-macbook-air-2023" from the row with "store_id" 2.
What’s the exact sql we need to use for this?
2
Answers
Here is one way to do it with the
update
/join
syntax:Basically this selects rows with
store_id
4 (aliasu
), and then attempts to joins with another row that has the sametarget_path
andstore_id
4. When the join matches, the query updates the originalrequest_path
to that of the matching row.If you wanted a
select
rather than anupdate
, we would probably use window functions rather than a self-join:From what you’ve described, it sounds like you need to update the
request_path
of all rows withstore_id
= 4 based on therequest_path
from the rows with the sametarget_path
andstore_id
= 2.Here is a SQL command that can achieve this:
The
UPDATE
clause updates theurl_rewrite
table, which we alias ast1
.The
INNER JOIN
clause combines rows fromurl_rewrite
(aliased ast2
) andt1
if they have the sametarget_path.
The
SET
clause changes therequest_path
oft1
to therequest_path
oft2
.The
WHERE
clause specifies the condition under which theUPDATE
statement will be executed – whenstore_id
is 4 int1
and 2 int2
.Please create a database backup before running the above query or run it first on a development environment, as it may result in irreversible changes. Also, the question may take a long time, depending on the size of your table. You might want to consider running it in a low-traffic period.