Jump to content

Finding unique values


johnsmith153

Recommended Posts

I have a simple db with values.

 

I want to find all duplicate values and rename them 1,2,3 - so if I have these values for a 'colour' field:

 

pID / color

 

1 / brown

2 / blue

3 / red

4 / red

5 / brown

 

...would result in:

 

1 / brown1

2 / blue

3 / red1

4 / red2

5 / brown2

 

...is this possible?

Link to comment
Share on other sites

Ok, Well I have just had a play around and have come up with something that will work but its far from perfect, it may (read: will) require some changes, unless you are happy with the result.

SET @count = 0;
UPDATE `table` JOIN (
SELECT `colour` FROM`table`
GROUP BY `colour`
    	HAVING COUNT(*) > 1
) AS `dupes` ON `chas`.`colour` = `dupes`.`colour`
SET `table`.`colour`= CONCAT(`table`.`colour`,@count := @count + 1)

The issue this code has is that "count" does not get returned to 0 when the GROUPED `colour` changes.

So from your example, the output would be something like

1 / brown1

2 / blue

3 / red2

4 / red3

5 / brown4

 

To counter this, you could add a WHERE clause and do each colour individually.

(Remember, if running this from PHP: mysql_query only supports a single query per call of the function)

Link to comment
Share on other sites

Thanks for offering this solution.

 

The problem is that the 'colour' field could be anything, so I really need a solution where it automatically picks up all duplicated rather than needing to know a set list of colours.

 

Would it help to have PHP assist in some way rather than doing it all in MySQL?

Link to comment
Share on other sites

You could do it in PHP, a quick select

SELECT `colour` FROM`table`
GROUP BY `colour`
    	HAVING COUNT(*) > 1

Will return all the colours that have a duplicate value.

You could then loop through this result set and use it to execute the query I posted above, OR use PHP to keep track of the count and individually update them.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.