0

I am looking to do the opposite of the solution listed here:

MySQL Insert row, on duplicate: add suffix and re-insert

by: https://stackoverflow.com/users/296452/andreas-wederbrand

I want to append the suffixes to the older (existing) value(s) in the table.

Hence I would have this result:

enter image description here

And if I try to insert dude again, the trigger will check if it exists, then append the next available (-3 in this case) to the existing one, and insert the newest dude WITHOUT a suffix:

enter image description here

Is this possible?

Thanks in advance. Chris

PAPADOC
  • 45
  • 1
  • 6

1 Answers1

0

A trigger in MySQL cannot act on the table which caused it to fire, hence your plan will not work, at least not as you described it. What you are asking for is going to be very difficult, if not impossible, to do, and would probably end up being a maintenance nightmare. I actually don't see any point to labelling the slug values with versions. I can offer a workaround, namely just building the version suffix at the time you query. This is fairly painless, and frees you from having a draconian table design. Something like this:

SET @rank = 0;
SET @slug = NULL;

SELECT
    t1.id,
    CASE WHEN t2.id IS NULL
         THEN CONCAT(t1.slug, '-', CAST(t1.label AS CHAR(50)))
         ELSE t1.slug END AS slug
FROM
(
    SELECT
        id,
        @rank:=CASE WHEN @slug = slug THEN @rank + 1 ELSE 1 END AS label,
        @slug:=slug AS slug
    FROM yourTable
    ORDER BY slug, id
) t1
LEFT JOIN
(
    SELECT slug, MAX(id) AS id
    FROM yourTable
    GROUP BY slug
) t2
    ON t1.id   = t2.id AND
       t1.slug = t2.slug;

Output:

enter image description here

Demo here:

Rextester

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I shouldn't have mentionned the ID column, I want all this to rely on the 1 slug column – PAPADOC Jul 26 '17 at 06:47
  • @PAPADOC Without the `id` column your question makes no sense because you need a column to provide ordering. I spent my entire lunch break writing and testing this query and I won't do any more. Good luck. – Tim Biegeleisen Jul 26 '17 at 06:51
  • Thanks for setting me on a different way of seeing this Tim, I will go about it a different route. – PAPADOC Jul 27 '17 at 03:54