0

I have below table structure

ITEM
| ID(Auto Inc)    | ORG_ID(FK to ORG)    | ITEM_ID               |
|-----------------|----------------------|-----------------------|
| 1               | 1                    | 1 (Initial Val for A) |
| 1               | 2                    | 1 (Initial Val for B) |
| 1               | 1                    | 2 (Incremented for A) |


ORG
| ID   | NAME      |
|------|-----------|
| 1    | A         |
| 2    | B         |

Is there any possibility of using any generator to manage item_id column. This is not id column for ITEM table. Business requirement is to manage item_id sequential for each org.

Jaydeep Patel
  • 2,394
  • 1
  • 21
  • 27

1 Answers1

0

You may try to insert using the next query:

INSERT INTO item (org_id, item_id)
SELECT @org_id, COALESCE((SELECT 1 + MAX(item_id)
                          FROM item
                          WHERE org_id = @org_id), 1)

where @org_id is the value to be inserted.

The problem: it may insert duplicates while concurrent insertions occures.

Akina
  • 39,301
  • 5
  • 14
  • 25