0

I have a table racuni which has a column id_racuna that only has NULL values in it.

enter image description here

This is the table creation query:

CREATE TABLE racuni
(
    id_interesa     INT UNSIGNED    NOT NULL AUTO_INCREMENT,    
    id_racuna       INT UNSIGNED    NULL,
    PRIMARY KEY (id_interesa)
) ENGINE=InnoDB;

As you can see, AUTO_INCREMENT has already been used on the primary key so I can't use it anymore to increment id_racuna. So I tried to use this query:

UPDATE racuni
SET id_racuna = CASE
                    WHEN (SELECT id_racuna FROM racuni ORDER BY id_racuna DESC LIMIT 1) IS NULL THEN 1
                    ELSE id_racuna +1
                END
WHERE id_interesa IN (2);

But I get an error:

enter image description here

I have seen people using aliases to solve this problem but they usualy deal with INSERT statements, so I am kind of lost here. How could I use aliases in my case? In the book from Ben Forta I read that aliases are provided using AS keyword, but people on this forum don't use it...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
71GA
  • 1,132
  • 6
  • 36
  • 69

1 Answers1

1

You seem to want:

set @id := 0;
update racuni r 
    set id_racuna = (@id := @id + 1);

I don't know where the condition on id_interesa comes in.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Could you explain this a bit? This is the first time I see `:=`. And why do you say `update racuni r`? – 71GA Jul 30 '17 at 06:22
  • @71GA . . . That is variable assignment. It is rather important in MySQL/ MariaDB because these databases lack other functionality (such as CTEs and window functions). – Gordon Linoff Jul 30 '17 at 19:42