简体   繁体   中英

Creating a sequence scheme in MYSQL without AUTO_INCREMENT

I want to run a sequence, scoped to each client so they each have a series of ID's starting from 1:

Clients:
+----+-------+
| id | name  |
+----+-------+
|  1 | Dave  |
|  2 | Sarah |
+----+-------+

Tickets:
+----+-----------+----------+----------------------------+
| id | clientID  | sequence |  title                     |
+----+-----------+----------+----------------------------+
|  1 |         1 |        1 | Title 1                    |
|  2 |         1 |        2 | Another title for Client 1 |
|  3 |         2 |        1 | Different Title            |
+----+-----------+----------+----------------------------+

Whats the best way to do this (in terms of speed and data integrity)? I have something like this upon inserting:

Add new ticket for Dave

SELECT COALESCE( (MAX(sequence) + 1), 1) as nextSeq WHERE id = 1 FROM tickets

then

INSERT INTO tickets (... sequence) VALUES (... nextSeq)

What's the COALESCE for?

When ever the record is first in it's series, the MAX() will return empty, so default empty to 1.

Why I want a user-scoped sequence number?

It's a document capture system, displaying lots of tabular data, I have multiple entities; System, Risk, Ticket, Process and I'm using numbers with titles to help users keep track of their records. Whilst in tables, the initial result will be ordered by this ID, hence I don't want a global ID numbering. I leave the auto_incremented column for other backend operations, joins, private referencing etc.

You could do this as one statement

   INSERT 
     INTO ticket (clientID, sequence, title)
   SELECT clientID,
          MAX(sequence) + 1,
          "Dave's New Ticket"
     FROM ticket
    WHERE clientID = 1 /** Dave */
 GROUP BY clientID

.. but I'm not totally sure about the performance compared to two separate statements. Note, the GROUP BY is actually optional in MySQL

It is also worth questioning whether a sequence number is in itself absolutely necessary, and what you are trying to accomplish with it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM