Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I have a version table using a field to track order:

id, owner_id, order, version
5, 1, 1, 1.1
6, 1, 4, 1.2
7, 1, 7, 1.2.1
8, 1, 10, 1.3

I want to ALTER TABLE version ADD COLUMN parent_id and have each record reference their parent and then drop the order column. The parent_id is the next lowest in order (which may not be sequential) resulting in:

id, owner_id, parent_id, version
5, 1, NULL, 1.1
6, 1, 5, 1.2
7, 1, 6, 1.2.1
8, 1, 7, 1.3

Can I write a query that will update the parent_id for me? Or must it be done programmatically?

share|improve this question

1 Answer 1

up vote 2 down vote accepted
CREATE TEMP TABLE v2
    SELECT * 
    FROM version;

UPDATE version v1 
SET parent_id = (
    SELECT id 
    FROM v2 
    WHERE v2.order < v1.order 
    ORDER BY v2.order DESC LIMIT 1
);
share|improve this answer
    
(Putting this here for other's reference) (stupid enter key) To avoid the error about not being able to select from the table you're updating, create a temp table first, do to the select from, like this: CREATE TEMP TABLE v2 SELECT * FROM version –  Utoxin Sep 6 '11 at 21:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.