2013-03-25 91 views
8

我有使用mySQL的問題。無效的空值使用

此錯誤彈出:

Invalid use of null value

我試圖在一個表的主鍵,使兩種屬性;這裏是我的代碼:

alter table contact_info 
add primary key(phone_number, contactID); 

下面是ALTER語句我把我的contact_info表:

alter table contact_info 
add contactID varchar(10); 

alter table contact_info 
add suffixID varchar(8); 

alter table contact_info 
add titleID varchar(12); 

alter table contact_info 
add companyID varchar(12); 

alter table contact_info 
add phonetypeID char(2); 

有誰知道什麼是錯?提前致謝。

回答

9

查找在phone_number或contactID中具有空值的contact_info。您無法在表中添加具有空值的主鍵。

select * 
from contact_info 
where (phone_number is null or contactID is null) 

運行該SQL查找值爲空的任何記錄。更新記錄,然後嘗試再次應用您的主鍵。

我不確定你在做什麼,但你可能想要先備份你的數據!在運行任何更新之前運行。這裏是您可能能夠使用設置的ContactID更新:

update contact_info 
set contactID = (select max(contactID) from contact_info) + 1 
where contactID is null 

update contact_info 
set phone_number = '555-1212' 
where phone_number is null 

如果你在你的數據副本,你需要找到它們並更新那些爲好。以下是如何找到重複項的方法:

-- Assuming the phone_number is duplicate (2 people living in the same house with the same phone number) 
select a.phone_number, count(1) 
from contact_info a 
group by a.phone_number 
having count(1) > 1 
+0

我現在正在爲'primary'主鍵獲得重複條目''。 這是什麼意思? – 2013-03-25 03:09:31

+0

一個主鍵,不管它是一個列還是2個,都不能有重複。我會幫你搜尋重複的東西。 – Jess 2013-03-25 03:11:06

1

運行此查詢將告訴您違規列的位置。您不能將NULL值設置爲主鍵。

SELECT * 
FROM contact_info 
WHERE phone_number IS NULL 
OR contactID IS NULL 
+0

我現在正在爲'主'主鍵獲取重複條目''。那是什麼意思? – 2013-03-25 03:10:14