mysql update a table from another 1 to 1 table

时间:2016-10-20 12:47:25

标签: php mysql sql

I have two tables, one is product and one is product_data

The product is master table and product_data is detail table but with 1 to 1 relationship on id column

I have some data in product_data which I want to update in product table

This is the query I use:

update product p 
       inner join product_data pp on p.catid=5 and p.id = pp.id
  set p.minp = pp.minp, p.maxp = pp.maxp, p.stores = pp.stores

It works fine, but when there are millions of records... it goes very slow and takes a lot of time

Is there some more optimized way to achieve this...?

I can use php code as well to optimize it, so the method does not necessarily have to be mysql specific.

Thanks in advance

2 个答案:

答案 0 :(得分:1)

Updating the table by using a join should already be the fastest way to update your data.

Make sure you have these indexes

  • product_data(id)
  • product(catid, id)

You can get it even a bit faster by adding a covering index:

  • product_data(id, minp, maxp, stores)

答案 1 :(得分:0)

You are likely violating normalization by copying values in the 1:1 relationship between tables. Leave the records in place in the product data file and use a VIEW.