开发者

MySQL INSERT ...SELECT with SUBQUERY

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, asoc开发者_高级运维iados

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'


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜