开发者

Mysql problem to store only different data

开发者 https://www.devze.com 2022-12-22 08:47 出处:网络
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 d

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号