r/DatabaseHelp • u/marcus13345 • Aug 16 '15
Auto increment + Group by?
Im wondering if its possible, using MySQL, to have a table in which a column is incremented only when it has a record with the same grouped ID. allow me to demonstrate:
assume i have a table
tbl_groupEntries (
row_id int PK AI,
group_id int NN,
entry_id int NN,
entry TEXT NN );and some data
1, 1, 1, 'random text'
2, 1, 2, 'test'
3, 2, 1, 'bippidy'
4, 2, 2, 'boppidy boo'`i want to create a constraint such that insert into tbl_groupEntries (group_id, entry) values (2, 'please work?');
inserts the row
5, 2, 3, 'please work?'
because 3 is the next ID for group 2 and the 5th ID overall.
edit: I have found a viable solution, if you find yourself in with the same issue, here is the solution. many thanks to u/muchargh for the SQL tips and u/wolf2600 for the base concept. :)
View all comments
Show parent comment
1
u/wolf2600 Aug 16 '15
What he's saying is that even the literals won't return if the group_by doesn't find a matching value already existing.
so I said you'd have to wrap the literals in nvl also, but thinking about it some more, you shouldn't have to. You'd just wrap the max(entry_id) in an nvl, so if the select didn't return anything, the nvl would still produce a single record as the result.