如何使用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 +
+ ... | ... +
+++++++++++++++++++++
答案 0 :(得分:73)
这会为您提供带有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 |
答案 1 :(得分:20)
试试这个:
SET @rownr=0;
SELECT @rownr:=@rownr+1 AS rowNumber, rowID
FROM myTable
WHERE CategoryID = 1
在现代版本的MySQL中,您可以使用MySQL窗口: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;
答案 2 :(得分:18)
但是如果你在select语句中有group by
怎么办?计算将结束。
对于这种情况,我找到的唯一解决方案是嵌套选择:
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
答案 3 :(得分:0)
您可以使用此代码。我认为这是一个更简单的解决方案。
select ROW_NUMBER() OVER ( ORDER BY id ) AS Seid, id from table1 where id<10
结果:
| 1 | 5|
| 2 | 7|
| 3 | 8|
| 4 | 9|