Reply to Re: Determining whether to INSERT or UPDATE

Your name:

Reply:


Posted by NC on 01/02/08 04:38

On Jan 1, 4:50 pm, "Aaron Gray" <ang.use...@gmail.com> wrote:
>
> I have a MySQL table of pages each with a 'title' and 'page'
> fields.
>
> How do I do either an UPDATE if the pages 'title' exists or
> an INSERT if it does not ?

Assuming that `title` is a primary or unique key, it's very simple:

INSERT INTO `pages` (`title`, `page`)
VALUES ('My Title', 'My Page')
ON DUPLICATE KEY UPDATE `page`='My Page'

See MySQL documentation for more information:

http://dev.mysql.com/doc/refman/4.1/en/insert.html

Alternatively, you can issue a REPLACE query:

http://dev.mysql.com/doc/refman/4.1/en/replace.html

The difference is that with INSERT ... ON DUPLICATE KEY UPDATE, you
can update an existing record partially (i.e., if there are fields
other than `title` and `page`, they will be kept intact). REPLACE,
however, deletes an existing row (if it exists, that is) before
writing a new one, so any fields not explicitly set by the REPLACE
query will be set to their default values.

Cheers,
NC

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация