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
https://forums.phpfreaks.com/topic/248612-finding-unique-values/
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)

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?

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.