如何在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 + + ... | ... + +++++++++++++++++++++
这将为您提供一个 连续的 行号3。
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 ;
结果
| ROWNUMBER | ROWID | --------------------- | 1 | 1 | | 2 | 25 | | 3 | 33 | | 4 | 150 |