我在 mysql 中有一个简单的表,它有不同类型的记录,由列中的值区分ptype
我的桌子看起来像这样
id1...ptype..usr...项目
1.....43.......2......7001
2......44.......2. ......8001
3......43......2......7002
4......43......2......7003
5.....43.......3......7001
当我添加一条新记录时,我需要我的查询在item
列中插入一个自动递增的值,基于ptype
并特定于usr
. 即,如果我插入一条新记录
id1...ptype..usr...item
6.....43........3......?
对于 ptype=43 和 usr=3 id1...ptype..usr...item
6.....43....3...... 7002
如果我们为 ptype=44 和 usr=2 添加另一条记录 id1...ptype..usr...item
7.....44.......2......8002
我想我应该先用item
空白插入新记录,然后使用 CASE WHEN THEN 方法用从新记录(即@lastid)派生的信息更新该记录,但它不起作用。
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);
更新 a1 SET item
= @item WHERE id1 = @lastid
照原样,@item 最初返回 0 的值,无论新记录具有什么“ptype”,并且为后续条目增加 1.... 我需要在每个 ptype 中添加的第一条记录为 5001 6001, 7001 , ETC。