我有一个简单的查询,比如:+ H [0 f4 d1 j& H0 s# K3 s
SELECT name FROM people;该people表没有唯一ID列。我想添加查询结果列。id增量int从0或1开始(这不重要)。一个人怎么能做到这一点?(PostgreSQL数据库)6 N. Y: ~5 a' ?7 j4 A* T& R9 }
% K% s& y& r- [7 u 解决方案: 3 d4 }' [4 A/ e2 z7 ] 用途ROW_NUMBER(): , g) Y/ y p# p$ p, F' ?) jSQLFiddle 5 k. L0 Z% }/ T2 r0 r, \; QSELECT name, ROW_NUMBER() OVER (ORDER BY name) AS idFROM people;编辑: ( B+ y% a9 q5 Z2 kORDER BY 1vs之间的区别ORDER BY column_name8 `& ]6 v. F5 h+ V1 b
SQLFiddleDemo) i0 j/ J( S5 t% J b, A) {: @
SELECT name, ROW_NUMBER() OVER (ORDER BY name) AS idFROM people;/* Execution Plan */QUERY PLAN WindowAgg (cost=83.37..104.37 rows=1200 width=38)-> Sort (cost=83.37..86.37 rows=1200 width=38)**Sort Key: name**-> Seq Scan on people (cost=0.00..22.00 rows=1200 width=38)SELECT name, ROW_NUMBER() OVER (ORDER BY 1) AS idFROM people;/* Execution Plan */QUERY PLAN WindowAgg (cost=0.00..37.00 rows=1200 width=38)-> Seq Scan on people (cost=0.00..22.00 rows=1200 width=38)第二种情况下,没有排序操作。; ^# y4 L3 I: I. z+ p6 g
您还可以将第二二个查询:7 n: G. E) ]7 w5 e
SELECT name, ROW_NUMBER() OVER () AS idFROM people;人们为什么ORDER BY 1在窗口函数中编写代码? 4 I8 o$ I" m. q% H0 O因为在某些方言中,它是必要的,而且ORDER BY 1充当占位符。/ c+ P U! @2 `
甲骨文: 4 E. }( v+ F" j* _5 @' s( Y! eORA-30485:窗口规范中缺少ORDER BY表达式 1 d& s1 D7 ]; H9 U. G, m8 ]SELECT name, ROW_NUMBER() OVER (ORDER BY 1) AS idFROM people;TSQL:5 C+ I; M# J0 z+ u
函数“ ROW_NUMBER必须有带有ORDER BY的OVER子句。 ) r( B- I9 x# N2 V' LSELECT name, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS idFROM people;