我有简单的查询,如:
SELECT name FROM people;
people
表没有唯一的id列。我想添加到查询结果列id
,增量int
从0/1开始无关紧要。怎么做到这一点? (postgresql DB)
答案 0 :(得分:10)
使用ROW_NUMBER()
:
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;
修改强>
ORDER BY 1
与ORDER BY column_name
SELECT
name,
ROW_NUMBER() OVER (ORDER BY name) AS id
FROM 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 id
FROM 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)
在第二种情况下,没有排序操作。
您还可以将第二个查询写为:
SELECT
name,
ROW_NUMBER() OVER () AS id
FROM people;
为什么人们在窗口函数中编写ORDER BY 1
?
因为在某些方言中它是必需的,ORDER BY 1
就像占位符一样。
Oracle:
ORA-30485:窗口规范中缺少ORDER BY表达式
SELECT
name,
ROW_NUMBER() OVER (ORDER BY 1) AS id
FROM people;
TSQL:
函数'ROW_NUMBER'必须具有ORDER BY的OVER子句。
SELECT
name,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS id
FROM people;
答案 1 :(得分:1)
如果仅在运行查询时需要它,则可以使用row_number
。
select row_number() over(order by name) as id, name
from people
答案 2 :(得分:1)
row_number
窗口功能应该适合账单:
SELECT ROW_NUMBER() OVER (ORDER BY 1), *
FROM people
答案 3 :(得分:1)
在https://www.postgresql.org/docs/current/static/functions-window.html
查看row_number()
功能