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

例如,我有一个2列, first_namelast_name与这些值的表

 Ali Khani Elizabette Amini Britney Spears ,... 

我想编写一个select查询来生成如下所示的表:

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

谢谢你的帮助。

如果是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

这里是支持窗口函数的SQL server, Oracle, PostgreSQL

 SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no, first_name, last_name FROM tableName 
  • SQLFiddle演示
 DECLARE @id INT SET @id = 0 UPDATE cartemp SET @id = CarmasterID = @id + 1 GO