How to change the primary key?

I deleted one row (row 20) in my “table category”, please let me know how can I reorder catid (primary key)? at this time it is 21 after 19.

thanks

+3
source share
10 answers

You can not. The closest thing you can get is that truncate tablewill drop the table and recreate it, which means that you will lose all the data in it, and the ID counter reset is 0. In addition, the identifier will always increase by one from the last inserted record , whether or not this entry exists. Of course, you can write a query to fix all of your current identifiers, but after the next insert, it will still create a new space. Moreover: if a sequential order without spaces is what you want, an automatic incremental identifier is not the right way to achieve this. Add another int field in which you manually track this ordering.

+6
source

, , .

, : " , ".

+5

. , , .

, , /. , .

+3

:

UPDATE tbl SET catid = (SELECT COUNT(*) FROM tbl t WHERE t.catid <= tbl.catid);

/. .

+3

.

, PHPmyAdmin

  • .

!

+2

, ? , , 20 21, , .

, , , 21 20

0

, ..

( ), , , _ , .

, , :

CREATE PROCEDURE [dbo].[OrganizeOrderConfirmationMessages] 
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @sortOrder INT;
    SET @sortOrder = 0;

    -- // Create temporary table
    CREATE TABLE #IDs(ID INT, SortOrder INT)

    -- // Insert IDs in order according to current SortOrder
    INSERT INTO #IDs SELECT ocm.ID, 0 FROM OrderConfirmationMessages ocm ORDER BY ocm.SortOrder ASC

    -- // Update SortOrders
    UPDATE #IDs SET SortOrder = @sortOrder, @sortOrder = @sortOrder + 10

    -- // Update the "real" values with data from #IDs
    UPDATE OrderConfirmationMessages SET SortOrder = x2.SortOrder
    FROM #IDs x2  WHERE OrderConfirmationMessages.ID = x2.ID    

END

:

SortOrders 1,2,5,7,10,24,36 10,20,30,40,50,60,70

0

"catid", , "Auto Increment", .

0

First, drag the primary key column from your table and run this syntax in the phppmyadmin sql section - ALTER TABLE 'your_tablename' ADD 'column_name' BIGINT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY ('column_name' (10));

This automatically arranges the column in numbers from 0, 1, etc.

0
source

try the following:

SET @var: = 0; UPDATE tableSET id= (@var: = @var + 1); ALTER TABLE tableAUTO_INCREMENT = 1;

0
source

Source: https://habr.com/ru/post/1724266/


All Articles