0

I have the following table:

- id (PK, int, Autoincrement)
- fk (foreign key, int)
- somedata (whatever)
- list_order (int)

I need to return somedata in order as defined by list_order for a given fk. No problem: SELECT somedata FROM myTable WHERE fk=123 ORDER BY list_order.

My question relates to how best to add a record should I wish it to be the last record for a given FK. Will I first need to do a MAX(list_order) for a given fk query, and then a separate query to insert the new row, or can I somehow do this in one query? Note that the order of the records might be changed, so I cannot simply get rid of list_order, and use ORDER BY id.

Thanks

4

1 に答える 1

2

1 つのクエリで実行できます。

INSERT INTO tableX
  ( fk, somedata, list_order)
SELECT
    fk, @somedata, MAX(list_order) + 1
FROM tableX
WHERE fk = @fk ;

同時挿入ステートメントが多数ある場合、2 つ (またはそれ以上) が同じ値をfkandlist_order列に挿入しようとする可能性があるという欠点があります。したがって、おそらく組み合わせにUNIQUE制約があるため(fk, list_order)、1 つを除いてすべてが失敗します。

于 2013-01-07T14:49:43.903 に答える