0

I have to do a insert query, inserting data from another table,

condition: if I have a 'codigoTipo' = 'A' , the column 'numero' should be the last 'numero' + 1

e.g.:

id | codigoTipo   |   numero 
1  |      A       |     1   
2  |      O       |     1   
3  |      A       |     2   
4  |      A       |     3   
   INSERT asociados (id, codigoTipo, numero, cp, direccion, email, fax, movil, nombre, nombreEncargado,  telefono, website, idLocalidad) 
    SELECT p.id, 'A', (MAX(asociados.numero)+1 ) , p.postalcode, p.address, p.mail, p.fax, p.movil, p.name, p.charge_person, p.phone, p.website, p.locality 
    FROM 
partners as p, asociados

How can I do that? My code has an error.

Edit: codigoTipo and numero, are a compositePK thats why I need the autoincremental number in column 'numero'

4
  • What is codigoTipo is not 'A', what should the value be? Commented Feb 21, 2011 at 19:53
  • codigoTipo can be 'A', 'O' or 'I' . Commented Feb 21, 2011 at 19:56
  • If codigoTipo is 'O' or 'I', what should the value of numero be? Commented Feb 21, 2011 at 20:01
  • codigoTipo and numero are a composite PK Commented Feb 21, 2011 at 20:04

1 Answer 1

3

You can use a subquery to get the maximum numero.

INSERT asociados (id, codigoTipo, numero, cp, direccion,
    email, fax, movil, nombre, nombreEncargado,  telefono, website, idLocalidad) 
SELECT p.id, 'A', dm.MaxNum + 1 , p.postalcode, p.address,
   p.mail, p.fax, p.movil, p.name, p.charge_person,
   p.phone, p.website, p.locality 
FROM partners as p, (SELECT MAX(numero) MaxNum FROM asociados) dm

Update: If you want the rows being inserted to increase, use this query:

INSERT asociados (id, codigoTipo, numero, cp, direccion,
    email, fax, movil, nombre, nombreEncargado,  telefono, website, idLocalidad) 
SELECT p.id, 'A', @r := @r + 1 , p.postalcode, p.address,
   p.mail, p.fax, p.movil, p.name, p.charge_person,
   p.phone, p.website, p.locality 
FROM partners as p, (SELECT @r := MAX(numero) MaxNum FROM asociados) dm
Sign up to request clarification or add additional context in comments.

4 Comments

Won't dm.MaxNum + 1 have the same value for all rows?
@ronnis It will, as far as i know the OP wants the same.
have a error with the updated query : "Duplicate entry 'A-0' for key 2"
@the-scrum-meister MAX(numero) was returning a NULL, because I don't have files yet, solved with this (SELECT @r := IFNULL(MAX(numero),0). thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.