I have a simple table in mysql that has different types of records, differentiated by a values in the column ptype
my table looks like this
id1…ptype..usr…item
1…..43…….2……7001
2…..44…….2……8001
3…..43…….2……7002
4…..43…….2……7003
5…..43…….3……7001
When I add a new record, I need my query to insert an auto incremented value in the item column, based upon ptype and specific to usr. i.e. if i insert a new record
id1…ptype..usr…item
6…..43…….3……?
it would add 1 to the highest number existing for ptype=43 and usr=3
id1…ptype..usr…item
6…..43…….3……7002
if we added another record for ptype=44 and usr=2
id1…ptype..usr…item
7…..44…….2……8002
i think i should do this by initially inserting the new record with item blank and then updating that record with information derived from the new record(i.e. @lastid) using the CASE WHEN THEN method, but it’s not working.
SET @lastid := LAST_INSERT_ID();
SET @ptype = (SELECT `ptype` FROM a1 WHERE `id1` = @lastid);
SET @item = (SELECT (
CASE
when @ptype = 41 then (SELECT 1 + coalesce((SELECT max(`item`) FROM `a1` WHERE `ptype` = 41 AND `plate`=7 AND `userid` = @userid), 5000))
when @ptype = 42 then (SELECT 1 + coalesce((SELECT max(`item`) FROM `a1` WHERE `ptype` = 42 AND `plate`=7 AND `userid` = @userid), 6000))
when @ptype = 43 then (SELECT 1 + coalesce((SELECT max(`item`) FROM `a1` WHERE `ptype` = 43 AND `plate`=7 AND `userid` = @userid), 7000))
when @ptype = 44 then (SELECT 1 + coalesce((SELECT max(`item`) FROM `a1` WHERE `ptype` = 44 AND `plate`=7 AND `userid` = @userid), 8000))
when @ptype = 45 then (SELECT 1 + coalesce((SELECT max(`item`) FROM `a1` WHERE `ptype` = 45 AND `plate`=7 AND `userid` = @userid), 9000))
when @ptype = 46 then (SELECT 1 + coalesce((SELECT max(`item`) FROM `a1` WHERE `ptype` = 46 AND `plate`=7 AND `userid` = @userid), 10000))
ELSE 0
end) as item
from
a1 WHERE `id1` = @lastid);
UPDATE a1 SET item = @item WHERE id1 = @lastid
as is, @item is returning values of 0 initially, no matter what ‘ptype’ the new record has, and is incrementing by 1 for subsequent entries…. i need the first record added in each ptype to be 5001 6001, 7001, etc.
First, the answer for which you didn’t ask: reverse your idea by creating the rows in their own tables (with an AUTO_INCREMENT as eggyal suggested) and then move the data to this table.
And now the answer:
Your information is a bit mis-matched, which might explain the problem or just be a red herring. For example, you don’t describe what ‘plate’ is, but you use it in your query. You also use @userid, which is not set in your examples.
I created a table that seemed to match your data at the top:
Then set the variable that you seemed to want:
and inserted a row:
pulled the id back out as you did:
Then you can get the max ‘item’:
To handle the initial case, you wanted a default. Since you’re separating the ptypes by 1000, you can use that:
Note that this isn’t thread safe, so wrap it all in a transaction/trigger.
Hope that helps.