Is there any easy way to update Column by Row number not a PK ex:
UPDATE contact m
SET ContactNumber = sub.rn + 500
FROM (SELECT Id, row_number() OVER (ORDER BY Id) AS rn FROM contact) sub
WHERE m.Id = sub.Id;
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It only takes a minute to sign up.
Sign up to join this communityUPDATE contact
SET ContactNumber = (@rownum := 1 + @rownum) + 500
WHERE 0 = (@rownum:=0)
-- for a given client, for example, Client_Id=123, use
-- WHERE Client_Id = 123 + (@rownum:=0)
ORDER BY id;
The syntax for using joins in UPDATE
in MySQL and MariaDB is: UPDATE a JOIN b ON ... SET ... WHERE ... ;
. The syntax you used UPDATE .. SET ... FROM ... WHERE ... ;
is used in SQL Server.
For recent versions of MariaDB that have window/ranking functions, the following will work:
UPDATE
contact AS m
JOIN
( SELECT Id, row_number() OVER (ORDER BY Id) AS rn
FROM contact
) AS sub
ON m.Id = sub.Id
SET
m.ContactNumber = sub.rn + 500
;
Tested in dbfiddle.uk
I got the answer :)
UPDATE contact m
join
(
SELECT Id, @rownum:=@rownum+1 rownum FROM contact
CROSS JOIN (select @rownum := 0) rn
order by contact.Id
) as sub on sub.Id= m.Id
set m.ContactNumber = sub.rownum + 500
where m.Client_Id=1