Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Troubleshooting
Research
Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

MySQL join with group / limit / random

Avatar of Ross Edwards
Ross EdwardsFlag for United Kingdom of Great Britain and Northern Ireland asked on
PHPMySQL ServerSQL
7 Comments1 Solution528 ViewsLast Modified:
I have two tables (simplified for clarity):

tblCustomer (id, my_brand, my_size, my_style, product_id)

tblProducts (id, size, brand, style)

I need to update tblCustomer.product_id with the id of a row from tblProducts, which matches on size, brand and style.

For example

update tblCustomers c set c.product_id =
(select p.id from tblProducts where
c.my_size = p.size and
c.my_style = p.style and
c.my_brand = p.brand
order by rand() limit1)

This works OK, but takes far too long to execute.  My tables are all correctly indexed.  There are around 500,000 cuxtomers to update, and 10,000 possible products, and for each customer I need to execute this query 30 times to populate different product options.

Is this the most efficient way of doing this query?

At the moment it takes about 20 mins for the above query, and my full process takes about 3 hours, which is not acceptable.

Many thanks!

Ross.