J'ai une grande table avec plusieurs colonnes représentant des événements liés. Cela inclut les colonnes id et nextId , où id signifie id d'un événement1, et nextId suggère dans quel autre événement cet événement1 a été utilisé. Cependant, il n'y a pas de colonne ' prev_id ' qui indiquerait quel event0 a contribué à event1. Est-il possible de construire une requête qui générera pour moi une telle table sans prendre un temps d'exécution très long?
Voici un exemple de ce que je veux dire:
prev_id | id | next_id 2 | 10 | 34 4 | 5 | 67 16 | 22 | 23
Voici ce que je veux avoir:
id | nextId 10 | 34 5 | 67 22 | 23 2 | 10 16 | 22 4 | 5
p>
3 Réponses :
Vous pouvez utiliser une join :
select t.id as prev_id, t.nextid as id, tnext.nextid as next_id
from t join
t tnext
on tnext.id = t.nextid;
Vous n'avez besoin que d'une auto-jointure.
Mais pour des raisons de lisibilité, je vous recommande d'utiliser un CTE:
with prevs as (
select nextid as id, id as previd from ids
)
select previd, id, nextid
from ids
join prevs using(id)
;
previd | id | nextid
--------+----+--------
4 | 5 | 67
2 | 10 | 34
16 | 22 | 23
(3 rows)
En plus de ce que d'autres ont dit, vous pouvez également accomplir cela à l'aide de requêtes hiérarchiques.
WITH test_data AS (
SELECT 10 AS ID,34 AS nextID FROM DUAL
UNION SELECT 5,67 FROM DUAL
UNION SELECT 22,23 FROM DUAL
UNION SELECT 2,10 FROM DUAL
UNION SELECT 16,22 FROM DUAL
UNION SELECT 4,5 FROM DUAL
)
SELECT h.*
FROM (
SELECT PRIOR t.ID AS prevID,
t.ID,
t.nextID
FROM test_data t
CONNECT BY t.ID = PRIOR t.nextID
) h
WHERE h.prevID IS NOT NULL
ORDER BY h.prevID