0

I have an sql command that returns me a list of duplicated items (in my MySQL database), only two columns, one for the duplicated value and one for the count of duplicated records.

SELECT title, COUNT(*) c FROM posts GROUP BY title HAVING c > 1

title         c  
---------------
title_1       2 
title_a       2
title_b       2

I assume one result looks like this:(and it's an array of arrays)

objId   title
------------
1    title_1 
2    title_1

So my goal is to append a string to the second item of a result in the array of the duplicated record's like this:

objId   title
------------
1    title_1 
2    title_1_2 

I've found a solution to update the record, but I don't have an idea how could I loop through the results that I get after the first sql command so I can't utilize it in practice.

UPDATE posts SET title = CONCAT(IFNULL(title,''), ' 2');

In pseudo code I would do something like this to create the new string for the title:

result[1].title = (oldTitleString," 2");

save result[1];

I'm new in sql and don't really know about the possibilities, maybe there would be an easier way to do it, so I would really appreciate if somebody could show me how can I get the second record from the duplicated item and extend it with another string.

2 Answers 2

1

My solution:

SELECT `objId`,`title`, 
(SELECT CONCAT(`title`, '_', `po`.`objId`) 
FROM `posts` `p` 
WHERE `title` = `po`.`title` && `p`.`objId` < `po`.`objId` LIMIT 1) AS `title_custom` 
FROM `posts` `po`
Sign up to request clarification or add additional context in comments.

Comments

0

Here is sample fiddle:

http://sqlfiddle.com/#!9/a4164/8

Query looks like this:

select id, title, 
concat(title,'_',
       (select count(*) from posts p2 where p2.title = p1.title and p2.id <= p1.id)),
title,
count(*)  c
from posts p1
group by title
having c > 1

Comments

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.