sql >> Database teknologi >  >> RDS >> PostgreSQL

SQL:Tilføj kolonne med trinvis id til SELECT

Brug ROW_NUMBER() :

SQLFiddle

SELECT 
  name,
  ROW_NUMBER() OVER (ORDER BY name) AS id
FROM people;

EDIT:

Forskellen mellem ORDER BY 1 vs ORDER BY column_name

SQLFiddleDemo

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)

I det andet tilfælde er der ingen sorteringsoperation.

Du kan også skrive anden forespørgsel som:

SELECT 
    name,
    ROW_NUMBER() OVER () AS id
FROM people;

Hvorfor skriver folk ORDER BY 1 i vinduesfunktioner?

For i nogle dialekter er det påkrævet og ORDER BY 1 fungerer som pladsholder.

Oracle:

SELECT 
  name,
  ROW_NUMBER() OVER (ORDER BY 1) AS id
FROM people;

TSQL:

SELECT 
    name,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS id
FROM people;


  1. TIMESTAMPDIFF() Eksempler – MySQL

  2. Databaseeffektivitet/strukturproblem

  3. Forespørgslen tager meget lang tid første gang den kører

  4. SELECT, der returnerer en liste over værdier, der ikke forekommer i nogen række