關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • MySQL 資料表重覆資料處理

    Posted on June 22nd, 2006 Sam Tang 1 comment

    在 MySQL 裡面想要避免 primary key 以外的資料重覆,可以在資料表裡面定義 UNIQUE 的欄位,例如:

    create table members(
       first_name char(20) not null,
       last_name char(20) not null,
       email char(50) not null,
       unique (first_name, last_name)
    );

    在以上建立 members 資料表的 SQL 語句中,最後一行用 unique 定義了 first_name 及 last_name 的資料不可以重覆,如果欄位已經存在相同的資料,MySQL 會輸出類似這句的錯誤訊息:

    "ERROR 1062 at line 1: Duplicate entry ‘xxx-yyy’ for key 1"

    有些情況要強制性地新增重覆資料,可以在 insert 加插 IGNORE,用法如下:

    insert ignore into members values(‘Sam’, ‘Tang’, ‘me@localhost’);


     

    One response to “MySQL 資料表重覆資料處理”

    1. [...] Real-Blog – MySQL 資料表重覆資料處理 (tags: Tech Database MySQL Tips) [...]

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word