Update record if exist, else insert in MySQL

五迷三道 提交于 2019-12-24 13:13:02

问题


I know, this question was asked many times and answered as well..
But, my problem is more specific and i couldn't found a proper solution.

My table (named as pages) is like that;

id (int)
title (text)
content (text)
slug (text)

I need to update my record if slug (i've converted it unique) is same as posted.

I mean i need to update/insert my record based on slug record.

Eg. current data:

  id  |  title  |  content  |  slug  |
--------------------------------------
  1  |  MainPage| some html | mainpage

if posted data has title=ChildPage, content=html.., slug=mainpage then i need to update previous record (title and content records), but if data has title=MainPage, content=html.., slug=other_slug then i need to insert this data as new with a new id.

UPDATE

Slug record was converted to UNIQUE key.


回答1:


The most appropriate thing I can imagine is to create a unique index on the slug column

ALTER TABLE pages ADD UNIQUE KEY slug;

The reason is simple: if this is not unique-constrained, there may be more than one slug with "mainpage"... which one should be updated??

then use ON DUPLICATE KEY UPDATE clause:

INSERT INTO pages 
VALUES (NULL, $title, $content, $slug) ON DUPLICATE KEY UPDATE content=$content


来源:https://stackoverflow.com/questions/11404243/update-record-if-exist-else-insert-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!