MySQL: How to get a sequential number with strings?

How can I calculate my results, where the lowest ID is No. 1 and the highest ID is #numberOfResults

Example. If I have a table with three rows. whose identifier is 24, 87, 112, it will look like this:

ID  24  87  112
Num 1   2   3

The reason I want this is because my manager wants the items to be numbered as item1, item2, etc. I initially made it so that it uses the ID, but he saw them as item24, item87, item112. He didn't like it at all, and they want them to be like item1, item2, item3. I personally think that this will lead to problems, because if you delete and add items, then item2 will not always refer to the same thing and can cause confusion for users. Therefore, if anyone has a better idea, I would like to hear it.

Thank.

+3
source share
4 answers

, ​​ , , . -, !

SELECT:

SELECT
    id,
    (@row:=@row+1) AS row
FROM table,
(SELECT @row:=0) AS row_count;

:

CREATE TABLE `table1` (
    `id` int(11) NOT NULL auto_increment,
    PRIMARY KEY  (`id`)
) ENGINE=InnoDB

INSERT INTO table1 VALUES (24), (87), (112);

SELECT
    id,
    (@row:=@row+1) AS row
FROM table1,
(SELECT @row:=0) AS row_count;

+-----+------+
| id  | row  |
+-----+------+
|  24 |    1 |
|  87 |    2 |
| 112 |    3 |
+-----+------+

@row - . SELECT. :

SELECT @row:=0;

:

SET @row:=0

. , , :

FROM table,
(SELECT @row:=0) AS row_count;

SELECT . , @row :

@row:=@row+1

@row , . , , . , ...

+11

, , - SQL. .

+2

?

, , - , , , . , .

0

CMS, . ", ", , .

, , , , , , , / . , , . . , . , .

..... . ....

0
source

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


All Articles