防止将空值插入主键列的表中

时间:2012-11-13 05:34:39

标签: mysql database primary-key

我不知道数据库是否有问题或者是什么问题。对于我的数据库中的所有表,对于声明为主键的列,在查询时采用NULL值或默认值

INSERT INTO TABLE (emp_name,emp_addr,emp_contact,salary) 
values ('Jack','127 N F 14 Stillwater','3456786543',8)

表格由emp_id(primary key), emp_name, emp_addr, emp_contact and salary组成。

如果我想用

插入一个元组
INSERT INTO EMPLOYEE values (NULL,'Jack','127 N F 14 Stillwater','345678543',8)

,它抛出的错误是主键不能为null,应该是。

我创建表的脚本是..

    create table Employee(
    emp_id int(11) primary key,
    emp_name varchar(25) not null,
    emp_addr varchar(40) not null,
    emp_contact varchar(10),
    salary float(2)
    )ENGINE=INNODB;

This is what is happening in my DB
 create table sale(sale_id varchar(10) primary key not null,sold_vehicle varchar(12),sm_id int(11),                                                                sale_date date)ENGINE=INNODB;
Query OK, 0 rows affected (0.01 sec)

mysql> insert into sale values('s2389','AP28DJ5093',1290,'05-12-2010');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> insert into sale values('s2420','AP28MY0545',1290,'24-10-2012');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from sale;
+---------+--------------+-------+------------+
| sale_id | sold_vehicle | sm_id | sale_date  |
+---------+--------------+-------+------------+
| s2389   | AP28DJ5093   |  1290 | 0000-00-00 |
| s2420   | AP28MY0545   |  1290 | 0000-00-00 |
+---------+--------------+-------+------------+
2 rows in set (0.00 sec)

mysql> update sale set sale_id = null where sale_id = 's2389';
Query OK, 1 row affected, 1 warning (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> select * from sale;
+---------+--------------+-------+------------+
| sale_id | sold_vehicle | sm_id | sale_date  |
+---------+--------------+-------+------------+
|         | AP28DJ5093   |  1290 | 0000-00-00 |
| s2420   | AP28MY0545   |  1290 | 0000-00-00 |
+---------+--------------+-------+------------+
2 rows in set (0.00 sec)

mysql> desc sale;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| sale_id      | varchar(10) | NO   | PRI | NULL    |       |
| sold_vehicle | varchar(12) | YES  |     | NULL    |       |
| sm_id        | int(11)     | YES  |     | NULL    |       |
| sale_date    | date        | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

2 个答案:

答案 0 :(得分:2)

您不能将主键字段设为null。并且您必须为主键放置非null。否则,拥有主键的重点是什么? :)请更改您的创建查询:

CREATE table tblblah(ID NOT NULL PRIMARY KEY, ...等等

;

INSERT INTO table tblblah(ID, .. ..等等

;

根据您的表架构填写它。

答案 1 :(得分:0)

在您的表格创建

上添加AUTO_INCREMENT选项
create table Employee
(
emp_id int(11) AUTO_INCREMENT primary key,
emp_name varchar(25) not null,
emp_addr varchar(40) not null,
emp_contact varchar(10),
salary float(2)
)ENGINE=INNODB;