如何在选择查询中生成自动增量字段


82

例如,我有一个包含2列的表,first_namelast_name具有这些值

Ali           Khani
Elizabette    Amini
Britney       Spears
,...

我想编写一个select查询,生成如下表:

1     Ali           Khani
2     Elizabette    Amini
3     Britney       Spears
,...

谢谢你的帮助。


1
您正在使用什么RDBMS?
peterm

Answers:


144

如果是MySql,可以尝试

SELECT @n := @n + 1 n,
       first_name, 
       last_name
  FROM table1, (SELECT @n := 0) m
 ORDER BY first_name, last_name

SQLFiddle

对于SQLServer

SELECT row_number() OVER (ORDER BY first_name, last_name) n,
       first_name, 
       last_name 
  FROM table1 

SQLFiddle


1
如果我想要什么,从seleect所有列table1,而不是first_namelast_name,我怎么可以参考呢?尝试SELECT @n := @n + 1 n, *不起作用
PlainOldProgrammer

答案是SELECT @n := @n + 1 n, table1.*
PlainOldProgrammer

1
在MYSQL中,您可能需要初始化@n: SET @n = 0;
Francisco R

2
@FranciscoR请仔细看看,它已经在子查询中初始化了(SELECT @n := 0)。这种方法的隐藏优点在于,您只有一个语句,而不是两个语句,这在客户端代码中禁止使用多个语句时是很好的选择。
peterm

33

这是SQL server, Oracle, PostgreSQL支持窗口功能的地方。

SELECT  ROW_NUMBER() OVER (ORDER BY first_name, last_name)  Sequence_no,
        first_name,
        last_name
FROM    tableName

4

在没有自然分区值的情况下,无论分区如何,都只需要有序号,就可以在常量上进行row_number的操作,在以下示例中,我仅使用了'X'。希望这可以帮助某人

select 
    ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1, 
    period_next_id, period_name_long
from 
(
  select distinct col1, period_name_long, 'X' as num
  from {TABLE} 
) as x

1
DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.