10

我在使用 mySQL 时遇到问题。

弹出此错误:

Invalid use of null value

我试图将表中的两个属性作为主键;这是我的代码:

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

以下是我放入我的contact_info 表的alter 语句:

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);

有人知道出了什么问题吗?提前致谢。

4

2 回答 2

11

在 phone_number 或contactID 中查找具有空值的contact_info。您不能在表中添加具有现有空值的主键。

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

运行该 SQL 以查找值为空的任何记录。更新记录,然后再次尝试应用您的主键。

我不确定你在做什么,但你可能想先备份你的数据!!!在运行任何更新之前。以下是您可以用来设置联系人 ID 的更新:

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
于 2013-03-25T02:54:52.790 回答
1

运行此查询将告诉您有问题的列在哪里。您不能将NULL值设置为主键。

SELECT *
FROM contact_info
WHERE phone_number IS NULL
OR contactID IS NULL
于 2013-03-25T02:56:14.143 回答