2014-05-22 36 views
0

在這個表中,我希望標題列在插入或更新行時不允許爲null(不能爲空)... 。用戶應該100%插入一些值,以便生成該行。mysql,更新後的列會得到空值,如何在插入和更新時不允許爲空

create table tab(id int not null auto_increment 
       primary key, 
       title varchar(255) not null); 
+-------+--------------+------+-----+---------+----------------+ 
| Field | Type   | Null | Key | Default | Extra   | 
+-------+--------------+------+-----+---------+----------------+ 
| id | int(11)  | NO | PRI | NULL | auto_increment | 
| title | varchar(255) | NO |  | NULL |    | 
+-------+--------------+------+-----+---------+----------------+ 

創建表。

我現在插入:

插入到標籤(idtitle)值(1, 'TITLE1'); ..... true

insert into tab(id)value(2); ......................... true --- - 這不應該是null。

mysql> select * from tab; 
+----+--------+ 
| id | title | 
+----+--------+ 
| 1 | title1 | 
| 2 |  | 
+----+--------+ 
2 rows in set (0.00 sec) 
+0

null或空字符串?也許你應該刪除默認值 – Uriil

+0

我怎麼可以使一列表不爲空,當用戶插入數據時,如果不是它只是給出錯誤和回滾,則應該使用100%的值。 – SAR

回答

0

將一個NOT NULL約束爲title列,並刪除default ''

原因default ''正在爲標題列插入默認空字符串,只要您不在insert中爲標題列提供值。

所以,如果你有你的模式,如下面插入值

create table tab(id int not null auto_increment 
       primary key, 
       title varchar(255) not null default ''); 

insert into tab(title) values('aaaaa'),('mmmmmm'),(''); 

那就試試下面的查詢,它將返回0行。所以基本上,title列中沒有NULL值,而是EMPTY STRING

select * from tab where title is null 

你的架構應該如下,

create table tab(id int not null auto_increment 
       primary key, 
       title varchar(255) not null); 

看到一個演示小提琴,如果你想進一步審查http://sqlfiddle.com/#!2/b5acf/3

+0

create table tab(id int not null auto_increment primary key, title varchar(255)not null); --------我創建這樣的表,然後插入值(插入到標籤('ID')值(1);現在插入的值當標題爲空(無值)時,應該運行查詢false,但它運行正確 – SAR

+0

@abas_rafiq,這是不可能的。你試過嗎?你發佈的評論是什麼。如果你嘗試它會拋出一個錯誤,因爲NOT NULL約束。使用該小提琴鏈接,並嘗試你所評論的。 – Rahul

+0

請檢查我的問題再次檢查我的問題它是geting空值我自我有點surprized ...我在做mistak – SAR