¿Seleccionar mientras se inserta?

I'm not sure if it's possible but I'm trying to do an insert while selecting for a value to do a +1. The reason I'm doing this is because my column is auto increments, but the values are all over the places.

Here's what I have so far and it won't let me do the insert:

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

preguntado el 31 de julio de 12 a las 11:07

4 Respuestas

Try using an alias in the sub-query. It did the trick for me.

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

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

Respondido 02 ago 12, 20:08

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

Respondido 31 Jul 12, 11:07

does not work am trying to do this directly into mysql not via a php page - elvoipman

If I've understood correctly your question try this!

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

Respondido 31 Jul 12, 11:07

I have tried this way previously and it still does not let me - it says that I can't specify target table "channels' from udpate in from caluse - elvoipman

Reiniciar auto-increment values you can try

SET @var_count = 0;

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

or

caer auto-increment column and recreate it with PRIMARY KEY en ella.

Respondido 31 Jul 12, 11:07

I would still need to do an insert... how can i do an insert and also take the last chanid of the respective equal values? - elvoipman

you can use LAST_INSERT_ID() to fecth last inserted id from table. - Omesh

please give me an example on how to do this - am not using php for this - elvoipman

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.