views:

88

answers:

2

I have a statement that looks something like this:

MERGE INTO someTable st
USING
(
    SELECT id,field1,field2,etc FROM otherTable
) ot on st.field1=ot.field1
WHEN NOT MATCHED THEN
    INSERT (field1,field2,etc)
    VALUES (ot.field1,ot.field2,ot.etc)

where otherTable has an autoincrementing id field.

I would like the insertion into someTable to be in the same order as the id field of otherTable, such that the order of ids is preserved when the non-matching fields are inserted.

A quick look at the docs would appear to suggest that there is no feature to support this.

Is this possible, or is there another way to do the insertion that would fulfil my requirements?

EDIT: One approach to this would be to add an additional field to someTable that captures the ordering. I'd rather not do this if possible.

... upon reflection the approach above seems like the way to go.

A: 

I am confused, why doesn't someTable also have a column called id? Wouldn't that solve your problem? If not, please clarify the problem with a concrete example.

Gandalf
someTable does have an id column. The issue here is that the id fields of both tables are auto-generated, so I can't just copy from one to another.
spender
+5  A: 

Why would you care about the order of the ids matching? What difference would that make to how you query the data? Related tables should be connected through primary and foreign keys, not order records were inserted. Tables are not inherently ordered a particular way in databases. Order should come from the order by clause.

More explanation as to why you want to do this might help us steer you to an appropriate solution.

HLGEM
+1 If you do care, there's something about the data that you're trying to capture that matters to you - so do it properly. It sounds like the data is telling you it wants an explicit order column.
Carl Manaster
The data that I am trying to insert is chronologically ordered, but does not have any explicit fields to indicate this ordering... however, the ordering in otherTable when sorted by id is chronologically correct. Thinking about your answer makes me wonder whether my schema could do with an update. You are correct that relying upon the id field is probably a dodgy approach.
spender