简体   繁体   English

在MYSQL中允许对索引列使用Null值还是对索引列使用NOT NULL? 什么是好的?

[英]Allow Null values for indexed column or NOT NULL for indexed column in MYSQL? What is good?

I am using MYSQL as database. 我正在使用MYSQL作为数据库。 Check is this table definition 检查是这个表的定义

CREATE TABLE `test`.`header`
( 
`header_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, 
`title` VARCHAR(500) NOT NULL, 
`body` VARCHAR(5000) NOT NULL, 
`created_by_id_ref` BIGINT UNSIGNED NOT NULL, 
`created_date` DATETIME NOT NULL, 
`updated_date` DATETIME NULL DEFAULT NULL, 
`is_void` TINYINT(1) NULL DEFAULT NULL,
PRIMARY KEY (header_id`) ) ENGINE=INNODB CHARSET=latin1 COLLATE=latin1_swedish_ci; 

In my interface user can delete any of the record by simply selecting the record from a grid view. 在我的界面中,用户可以通过简单地从网格视图中选择记录来删除任何记录。 So in that case I am simply updating the "is_void" status to true. 因此,在那种情况下,我只是将“ is_void”状态更新为true。

I declared that column by this syntax. 我用这种语法声明了该列。 which shows above. 如上所示。 Here it again. 再来一次

`is_void` TINYINT(1) NULL DEFAULT NULL,

So If I add an index to this column is this column declaration is good? 因此,如果我向该列添加索引,此列声明是否正确? In that case records default have null values. 在这种情况下,记录默认值为空值。 For voided records it will be "1". 对于无效的记录,它将为“ 1”。 So if I am going to filter any of those records for voided records I have to use 因此,如果我要过滤掉所有记录中的无效记录,就必须使用

Select ........ where is_void=1;

If I want to filter non voided records I can use 如果我想过滤未作废的记录,可以使用

Select ........ where is_void IS NULL;

So is this NULL declaration affect to my select query performance? 那么这个NULL声明会影响我的选择查询性能吗? (Remember I indexed this column) (请记住,我已将此列编入索引)

Or Shall I declare my column as 还是我将我的专栏声明为

`is_void` TINYINT(1) NOT NULL,

and then I have insert "0" for non voided records. 然后为无效记录插入“ 0”。 Then if I want to filter non voided records I can use 然后,如果我想过滤未作废的记录,我可以使用

Select ........ where is_void=0;

So What is the best? 那么什么是最好的? where is_void=0; 其中is_void = 0; or where is_void IS NULL; 或is_void IS NULL;

Thank you very much. 非常感谢你。

In terms of performances, both approaches are equivalent * . 在性能方面,这两种方法是等效的*

In terms of logic, NULL is widely regarded as meaning "unknown value" or "not applicable". 就逻辑而言, NULL被广泛认为是“未知值”或“不适用”。 Go with 1 or 0, as defined by the TRUE and FALSE constants . 按照TRUEFALSE常数的定义 ,选择1或0。

Also, even though MySQL implements it as an alias for TINYINT(1) , I would advise using the ANSI-standard BOOLEAN type . 另外,即使MySQL将其实现为TINYINT(1)的别名,我还是建议使用ANSI标准的BOOLEAN类型


* Ok, this is not entirely true in theory. * 好的,理论上并不完全正确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM