Sometimes data we are about to store have the same title and description a开发者_运维技巧s that we already have in our database. We do not wish to store data if the title and description of incoming data are the same as the title and description of already stored data. How would we do that?
Hey. Mark the columns that hold them UNIQUE
CREATE TABLE `myData` (
id serial primary key,
title varchar(255) unique,
description varchar(255) unique
);
If you want it to depend on both columns (meaning title can be the same as another row, as long as description is different from that row), then you can do this:
CREATE TABLE `myData` (
id serial primary key,
title varchar(255) not null,
description varchar(255) not null,
UNIQUE (title, description)
);
Create unique index from title and description.
Perform a SELECT on the title and description to determine whether they already exist. If they do then show appropriate error messages. If not then perform the INSERT
Edit: Note this focuses on the application logic. The other answers also address the database enforcement of this policy. Both go hand in hand.
精彩评论