0

I have a mysql table with columns: customer, dateOrder. One customer can have orders in multiple dates. I want to add a new column with the farthest date order for each customer. So far i tried this:

UPDATE mytable  
   SET MINDATE = (SELECT min(DATEORDER) 
                    FROM (SELECT * 
                            FROM mytable 
                           GROUP 
                              BY CUSTOMER
                          ) tblTmp
                 )

, where tblTmp is a temporary table;The problem is that it brings the same date for all my customers (the farthest date in the table). Any ideas?

1
  • If you like, consider following this simple two-step course of action: 1. If you have not already done so, provide proper DDLs (and/or an sqlfiddle) so that we can more easily replicate the problem. 2. If you have not already done so, provide a desired result set that corresponds with the information provided in step 1. - A tip is to start with a SELECT that returns the desired result, and then build up to the UPDATE Commented Jan 26, 2015 at 15:00

1 Answer 1

1

Use a JOIN to match the original table with the subquery:

UPDATE mytable AS t1
JOIN (SELECT customer, MIN(dateorder) AS mindate
      FROM mytable
      GROUP BY customer) AS t2 ON t1.customer = t2.customer
SET t1.mindate = t2.mindate
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! worked like a charm! I'm quite new with databases and I was avoiding the Join :)
Embrace the JOIN! it is the fundamental operation in relational databases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.