在mysql中使用'case'自动增加

时间:2012-06-05 01:41:27

标签: mysql case auto-increment coalesce

我在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 ...项目
6 ..... ....... 43 3 ......?

它会为ptype = 43和usr = 3现有的最高数字加1 ID1 ... ptype..usr ...项目
6 ..... ....... 43 3 ...... 7002

如果我们为ptype = 44和usr = 2添加了另一条记录 ID1 ... ptype..usr ...项目
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等

2 个答案:

答案 0 :(得分:1)

您可以使用触发器:

CREATE TRIGGER biA1 BEFORE INSERT ON a1 FOR EACH ROW SET NEW.item = (
  SELECT COALESCE(MAX(item), (NEW.ptype-36)*1000) + 1
  FROM   a1
  WHERE  ptype = NEW.ptype AND plate = 7 AND userid = NEW.userid
)

答案 1 :(得分:1)

首先,您没有问过的答案:通过在自己的表中创建行来反转您的想法(建议使用AUTO_INCREMENT作为eggyal),然后将数据移动到此表中。

现在回答:

您的信息有点不匹配,这可能解释了问题或只是一个红鲱鱼。例如,您没有描述'plate'是什么,但您在查询中使用它。您还使用@userid,但未在示例中设置。

我创建的表格似乎与您顶部的数据相符:

create table a1 (
  id1 int primary key auto_increment,
  ptype int,
  usr int,
  item int
);

然后设置您想要的变量:

set @userid = 2;
set @ptype = 43;

并插入一行:

insert into a1 (ptype, usr) values (@ptype, @userid);

将你的身份恢复原状:

SET @lastid := LAST_INSERT_ID();

然后你可以获得最大'项目':

select max(item) from a1  WHERE `ptype` = @ptype AND `usr` = @userid;

要处理初始案例,您需要默认值。由于您将ptypes分隔1000,您可以使用:

SELECT ifnull(max(`item`),(@ptype % 40 + 2)*1000)+1 as next
FROM `a1`
WHERE `ptype` = @ptype
AND `usr` = @userid;

+------+
| next |
+------+
| 5001 |
+------+

请注意,这不是线程安全的,因此请将其全部包含在事务/触发器中。

希望有所帮助。