There are 4 columns in my relationship table:
- ID
- CID – course id
- LID – related lesson unique id
- course_based_id – explanation below
There are bunch of lessons and courses with unique id’s in another tables called lessons and courses. This table is, asociation table between them. Basically it assigns unique lesson id to unique course id. But.. There is need for course based id of lesson. I mean, for example lets take a look at first and second rows from screenshot

Lid 1 is course 2’s first lesson, lid 3 is course 2’s second lesson… And so on. So if I insert cid 2, lid 128 it must third lesson of course 2.
Now, the problem is, I want to auto generate this number while insert:
$q="INSERT INTO `courses-lessons` (`cid`, `lid`) VALUES (?,?)";
but have no idea how to do it. Some MySQL function? or something inside query?
If you’re using MyISAM engine to store this table, this can be done relatively easy: you just define the fields this way:
Then any
INSERTwill automatically assign a new (+1) value forcourse_based_idbased oncid. Here’s a Fiddle illustrating this concept.You can find more info about it in MySQL documentation.
Unfortunately, there’s no such mechanism in InnoDB engine. So perhaps you can get away with the following routine (it’s a pseudocode, there are some nuances):
I’d suggest checking this answer; it’s for PostgreSQL, not MySQL, but describes one possible implementation in some details.
UPDATE: Here’s an example of actual set of queries implementing that behaviour:
As you see, there’s no direct calculation of the next
course_based_idvalue, yet we got the sequence here.