Understanding Mysql 'on duplicate key'
$update = "insert into mapa_etiquetas (nombre,urlimagen,id_usuario) values('$this->nombre', '$ruta', '$u') on duplicate key update urlimagen=valu开发者_如何转开发es('$ruta')";
I want to avoid what i do tipically
- SELECT if exists
- If exists
- Update
- Else
- Insert
Questions, will the sentence i wrote do that? The way i see it, if i call
$update = "insert into mapa_etiquetas ('casa','image.png',2)
values('$this->nombre', '$ruta', '$u')
on duplicate key update urlimagen=values('$ruta')";
$update = "insert into mapa_etiquetas ('casa','image2.png',2)
values('$this->nombre', '$ruta', '$u')
on duplicate key update urlimagen=values('$ruta')";
Result will be two elements in table with 'casa' name, right? (instead of editing urlimagen. becaus it will be considred different elements, right)
how could i do to, by one mysql sentence, update urlimagen (for nombre,iduser combination) and if no exists, insert it?
Thanks in advance!
the update urlimagen = values('$ruta')
is telling MySql to look for a column named the value of $ruta
. Change your statement to use the actual column name:
insert into mapa_etiquetas (nombre, urlimagen, id_usuario)
values ('$this->nombre', '$ruta', '$u'),
('$this->nombre', '$ruta2', '$u')
/*Add more rows here*/
on duplicate key update
urlimagen = values(urlimagen)
Your first query doesn't match your second code block.
First
$update = "insert into mapa_etiquetas (nombre,urlimagen,id_usuario)
values('$this->nombre', '$ruta', '$u')
on duplicate key update urlimagen=values('$ruta')";
Second:Incorrect
$update = "insert into mapa_etiquetas ('casa','image.png',2)
values('$this->nombre', '$ruta', '$u')
on duplicate key update urlimagen=values('$ruta')";
$update = "insert into mapa_etiquetas ('casa','image2.png',2)
values('$this->nombre', '$ruta', '$u')
on duplicate key update urlimagen=values('$ruta')";
The problem with your second block is that you are naming values where the column names should go. I believe the correct second block should be:
Second:Corrected
$update = "insert into mapa_etiquetas (nombre,urlimagen,id_usuario)
values('$this->nombre', '$ruta', '$u')
on duplicate key update urlimagen=values('$ruta')";
$update = "insert into mapa_etiquetas (nombre,urlimagen,id_usuario)
values('$this->nombre', '$ruta', '$u')
on duplicate key update urlimagen=values('$ruta')";
I also agree with @The Scrum Meister. Their answer should be heeded regarding appropriate use of the 'on duplicate key update' clause.
精彩评论