Update record if exist, else insert in MySQL

2019-08-11 07:52发布

问题:

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