agusgambina
agusgambina

Reputation: 6669

MySql update with different values a column for duplicate columns

I have a table like this

CREATE TABLE IF NOT EXISTS users_groups(
  id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id INT(11) UNSIGNED NOT NULL,
  name VARCHAR(250) NOT NULL,
  is_deleted BOOLEAN NOT NULL DEFAULT false,
  creation_date DATETIME NOT NULL,
  last_modification_date DATETIME NOT NULL,
  PRIMARY KEY (id)
);

And I would like to turn the columns (user_id, name) as unique, but the problem I have is that I already have duplicates in that columns. In some cases the columns are repeated many times.

I would like to write a query to update the duplicates rows concatenating some value in the name, for example concatening '*' for the first duplicate '**' for the second duplicate, and so on.

Is this possible writing a query?

I can get the group that I want to modify, but I am not sure if it is possible to achieve what I want with mysql

select users_groups.id, users_groups.user_id, users_groups.name
from users_groups
inner join (select user_id, name, count(*) from users_groups group by user_id, name having count(*) > 1) as u on u.user_id = users_groups.user_id
where users_groups.name = u.name;

Upvotes: 1

Views: 1011

Answers (2)

ydoow
ydoow

Reputation: 3006

Try this.

SET @prev_user_id := '';
SET @prev_name := '';
SET @cnt := 0;

select s.id, s.user_id, s.name
from 
(
  select 
    users_groups.id,     
    IF(@prev_user_id <> users_groups.user_id OR @prev_name <> users_groups.name, @cnt := 0, @cnt := @cnt + 1) AS cnt,   
    CONCAT(users_groups.user_id, REPEAT('*', @cnt)) AS user_id,
    CONCAT(users_groups.name, REPEAT('*', @cnt)) AS name,  
    @prev_user_id := users_groups.user_id,
    @prev_name := users_groups.name
  from 
    users_groups
) s

Check here: http://sqlfiddle.com/#!9/6d553/10

Upvotes: 1

Chris
Chris

Reputation: 815

I'm not sure if this helps, but you can make a column unique without it having to be the primary key of that table.

For example:

CREATE TABLE user (
    user_id NOT NULL,
    firstname varchar(255) NOT NULL,
    UNIQUE (firstname)
) 

Or the following statement which creates a unique constraint across multiple columns.

CREATE TABLE user (
    user_id NOT NULL,
    firstname varchar(255) NOT NULL,
    CONSTRAINT constraint_name UNIQUE (user_id, firstname)
) 

Also, I'm not entirely sure why you would want to identify duplicates. It's good practice to avoid duplicate records and data entries entirely. This can be done through table normalization, as well as the use of appropriate indexing.

I hope this helps in some way.

Upvotes: 0

Related Questions