0

所以我有这张表,我只想看 AB。

ID     CODE       COUNT   
102    AB         9
101    AB         8
100    AC         23    //not important!!!!
99     AB         7
98     AB         6
97     AB         5
96     AB         0

我希望这张桌子看起来像这样

ID    NEWID     CODE       COUNT   
102   102       AB         9
101   101       AB         8
99    100       AB         7
98    99        AB         6
97    98        AB         5
96    97        AB         0

如何获得一个在代码为 AB 的地方连续计数的新 ID?

然后将其用于 SELECT 查询,初始表应保持不变,因此这不是更新表,而只是制作虚构的 NEWID。

4

3 回答 3

1

您可以使用用户变量创建一个计数器来完成此操作(只需一个查询!):

SELECT t.ID, @NEWID := COALESCE(@NEWID - 1, t.ID) AS NEWID, t.CODE, t.COUNT
FROM
    (SELECT ID, CODE, COUNT FROM some_table WHERE CODE = 'AB' ORDER BY ID DESC) t,
    (SELECT @NEWID := NULL) _uv;
mysql> SELECT t.ID, @NEWID := COALESCE(@NEWID - 1, t.ID) AS NEWID, t.CODE, t.COUNT
    -> FROM
    ->     (SELECT ID, CODE, COUNT FROM some_table WHERE CODE = 'AB' ORDER BY I
D DESC) t,                                                                        
    ->     (SELECT @NEWID := NULL) _uv;
+------+-------+------+-------+
| ID   | NEWID | CODE | COUNT |
+------+-------+------+-------+
|  102 |   102 | AB   |     9 |
|  101 |   101 | AB   |     8 |
|   99 |   100 | AB   |     7 |
|   98 |    99 | AB   |     6 |
|   97 |    98 | AB   |     5 |
|   96 |    97 | AB   |     0 |
+------+-------+------+-------+
6 rows in set (0.03 sec)

编辑:这是一个SQL Fiddle。(多么酷的工具。我不知道这存在!)

于 2013-01-26T10:00:28.647 回答
0

尝试这个:

SELECT MIN(ID) - 1
FROM tab
WHERE CODE = 'AB'
INTO @i;

SELECT tab.ID, (@i := @i + 1) AS NEWID, tab.COUNT
FROM tab
WHERE tab.CODE = 'AB'
ORDER BY tab.ID;

另见http://sqlfiddle.com/#!2/2b52e2/1

于 2013-01-26T09:48:50.310 回答
0

你可以使用这个:

SELECT
   Id, @newid := @newid - 1 as NEWID, CODE, CNT
FROM Tbl,
(SELECT @newid := MAX(ID) + 1 FROM Tbl) A
WHERE CODE != 'AC'
ORDER BY NEWID DESC

SQL 小提琴

于 2013-01-26T09:47:36.257 回答