Q
Q
Quetzsalcoatl2016-01-21 20:13:58
PHP
Quetzsalcoatl, 2016-01-21 20:13:58

How to set a unique identifier for fields in a table in mysql?

Good day!
There is a table of this kind for storing images:
id, postid, xfield, xid, link
So, in addition to the unique id, there is also xid, which must be a unique increment, for unique xfield fields, that is, for each new xfield value, xid starts counting from the beginning .
id, postid, xfield, xid, link
1, 13, pole1, 1, /upload/1.jpg
2, 16, pole1, 2, /upload/2.jpg
1, 19, pole2, 1, /upload/3. jpg
I ask for help, because I myself, due to the low level of understanding of php and mysql, I can not solve this problem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-01-21
@petermzg

xid is not a unique increment. It will be unique across xfield entries.
Make a unique index [xfield, xid] + inserting data through a stored procedure, where
you modulate select max(xid) + 1 from table where xfield = value
Then insert with the received xid + 1, if an exception occurs at a unique index, then repeat.

R
Rsa97, 2016-01-21
@Rsa97

The most obvious way is to write a BEFORE INSERT trigger. In trigger, lock table, look up max `xid` for `xfield`, write next, unlock table.
Well, or do the same in the script itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question