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/marcus13345 Aug 16 '15 edited Aug 16 '15
right because then it will return 0s for the first id of a given group, if im understanding correctly.
edit: after testing with data already in the table, it works. so the problem im having definitely is coming from not having values already in there. it looks like specifically its when adding a record to a group that doesn't exist. i've tried wrapping each level of the potentially null column in ifNULLs and it still refuses to add the record.