47

如何使用 MySQL 在我的 select 语句中创建和自动增加临时列?

这是我到目前为止所拥有的:

SET @cnt = 0;
SELECT
    (@cnt =@cnt + 1) AS rowNumber,
    rowID
FROM myTable
WHERE CategoryID = 1

返回:

+++++++++++++++++++++
+ rowNumber | rowID +
+++++++++++++++++++++
+  (NULL)   |   1   +
+  (NULL)   |   25  +
+  (NULL)   |   33  +
+  (NULL)   |   150 +
+  (NULL)   |   219 +
+++++++++++++++++++++

但是我需要:

+++++++++++++++++++++
+ rowNumber | rowID +
+++++++++++++++++++++
+  1        |   1   +
+  2        |   25  +
+  3        |   33  +
+  4        |   150 +
+  ...      |   ... +
+++++++++++++++++++++
4

4 回答 4

98

这将为您提供一个连续的行号3

SELECT
    (@cnt := @cnt + 1) AS rowNumber,
    t.rowID
FROM myTable AS t
  CROSS JOIN (SELECT @cnt := 0) AS dummy
WHERE t.CategoryID = 1
ORDER BY t.rowID ;

结果

| 行号 | ROWID |
---------------------
| 1 | 1 |
| 2 | 25 |
| 3 | 33 |
| 4 | 150 |
于 2013-04-10T15:50:41.127 回答
31

但是,如果您group by在 select 语句中有 a 怎么办?计数将关闭。

对于这种情况,我发现的唯一解决方案是嵌套选择:

SELECT (@cnt := @cnt + 1) AS rowNumber, t.*
from
(select
    t.rowID
FROM myTable 
WHERE CategoryID = 1
ORDER BY rowID) t
CROSS JOIN (SELECT @cnt := 0) AS dummy
于 2014-03-16T05:14:28.600 回答
29

尝试这个:

SET @rownr=0;
SELECT @rownr:=@rownr+1 AS rowNumber, rowID
  FROM myTable
  WHERE CategoryID = 1

在 MySQL 的现代版本中,您可以使用 MySQL Window:http ://www.mysqltutorial.org/mysql-window-functions/mysql-row_number-function/

例子:

SELECT  ROW_NUMBER() OVER (  ORDER BY productName  ) row_num, 
        productName, msrp 
FROM   products ORDER BY   productName;
于 2013-04-10T15:48:15.647 回答
1

您可以使用此代码。我认为这是一个更简单的解决方案。

select ROW_NUMBER() OVER (  ORDER BY id  ) AS Seid, id from table1 where id<10

结果:

| 赛德 | 编号 |

| 1 | 5|

| 2 | 7|

| 3 | 8|

| 4 | 9|

于 2021-03-25T16:26:00.373 回答