2

I have a table with some data that has gone wrong, that I need to fix up. Below is an example:

TABLE-A
id, type, value
1, 10, 123456
2, 10, NULL
3, 10, NULL
4, 20, 123456
5, 20, 654321
6, 20, NULL

I need a MYSQL update command.

If the "type" is the same then update the "value" so it is the same as long as the value is NULL and the "value" is unique

UPDATE table-a SET value = (...)

So in the table above only id 2 and 3 will have the value updated to 123456

id 6 will not update as the "value" is not unique for the the same "type".

4
  • what should be value of "id"6 in above example as it can be updated to either 123456 or 654321? Commented Jul 2, 2011 at 10:28
  • It should not be updated, I will have to manually update these. Commented Jul 2, 2011 at 10:30
  • I would not suggest you do it in a single query.A single query can be complex.Use PHP or some other language,you are working with. Commented Jul 2, 2011 at 10:36
  • I am using PHP, but cant get my head around it. Commented Jul 2, 2011 at 10:38

1 Answer 1

4
UPDATE TABLE_A t
         JOIN
           ( SELECT type
                  , MIN(value) AS value
             FROM TABLE_A
             GROUP BY type
             HAVING COUNT(DISTINCT value) = 1
           ) AS tu
         ON tu.type = t.type
SET t.value = tu.value
WHERE t.value IS NULL

As Peufeu pointed, the DISTINCT is needed to catch cases like this one, where I suppose the id=3 row has to be updated, too:

TABLE-A
id | type | value
 1 |  10  | 123456
 2 |  10  | 123456
 3 |  10  | NULL
 4 |  20  | 123456
 5 |  20  | 654321
 6 |  20  | NULL
Sign up to request clarification or add additional context in comments.

3 Comments

count(value) is wrong here : you meant count(DISTINCT value) I guess.
@peufeu: Yeah, I guess COUNT(DISTINCT value) is more correct. It will catch cases where for a type there are two or more rows with exact same value and all other rows are NULL. Thnx.
works well for my example, thanks. however if the table has 7,30,123456 8,30,123456 9,30,NULL then ID 9 does not update

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.