2015-04-24 167 views
1

在解僱INSERT查詢時,是否有可能返回錯誤(或任何其他指示)如果我希望插入的值之一已經存在於表中?MySql重複返回錯誤

INSERT INTO `private_customers`(`first_name`, `phone_number`) 
VALUES ('the_first_name','1122334455') 
// if the phone number is already exist in the table then don't insert nothing and return indication that it is already exist 
+1

在'(phone_number)'上添加一個'唯一'約束? –

+0

如果你不想創建'UNIQUE'約束,只需要1.'SELECT'來檢查電話號碼是否已經存在,2.你的INSERT',3.利潤。 – cypher

+0

但是兩個私人客戶不能共享相同的號碼嗎? (例如,一對夫婦住在一起)。 – jarlh

回答

2

是,只需添加唯一索引:

create unique index idx_private_custoemrs_fn_pn on private_customers(first_name, phone_number); 

create unique index idx_private_custoemrs_fn on private_customers(first_name); 
create unique index idx_private_custoemrs_pn on private_customers(phone_number); 

如果希望值的是唯一的,然後在創建索引

(並且不包括其他兩個索引)。

+0

現在我在設置唯一約束並嘗試再次插入相同的值後出現重複錯誤,但是如何知道錯誤是否與重複有關?在這種情況下是否有特殊的錯誤編號或特殊值? – shmnsw

+0

我想是1062 .. – shmnsw

0

您可以簡單地添加一個唯一約束來實現它。