2012-07-31 101 views
1

我不确定是否有可能,但我正在尝试做一个插入,同时选择一个值做+1。我这样做的原因是因为我的列是自动增量,但值都遍布各地。插入时选择?

这里就是我有这么远,它不会让我做插件:

insert into channels set chanid=(select chanid from channels where parent=2 
order by chanid desc limit 1)+1 

回答

1

尝试在子查询中使用别名。它为我做了诡计。

insert into channels 
set chanid=(
    select c.chanid 
    from channels as c 
    where c.parent=2 
    order by c.chanid desc 
    limit 1 
)+1 

参考:http://bugs.mysql.com/bug.php?id=6980

+0

这 - 这工作完美无瑕,非常感谢! – thevoipman 2012-08-02 20:33:57

1
insert into channels(chanid) 
select chanid+1 from channels where parent=2 
order by chanid desc limit 1 
+0

不工作我试图直接不通过一个PHP页面 – thevoipman 2012-07-31 11:19:19

0

如果我理解正确你的问题试试这个!

insert into channels set chanid=(select chanid+1 from channels where parent=2 order by chanid desc limit 1) 
+0

做到这一点到MySQL我以前尝试过这种方式,它仍然没有让我 - 它说,我可以” t指定目标表“渠道”从udpate从caluse – thevoipman 2012-07-31 11:07:34

0

要重置auto-increment值,你可以尝试

SET @var_count = 0; 

UPDATE channels 
SET chanid = (@var_count := @var_count + 1); 

下降auto-increment柱,用PRIMARY KEY它重新创建它。

+0

我仍然需要做一个插入...我如何做一个插入,并采取各自的等值的最后chanid? – thevoipman 2012-07-31 11:05:43

+0

你可以使用LAST_INSERT_ID()来fecth最后插入的ID表 – Omesh 2012-07-31 11:07:27

+0

请给我一个关于如何做到这一点的例子 - 我没有使用PHP这个 – thevoipman 2012-07-31 11:19:49