我如何要求一个mysql字段? [英] How do I require a mysql field?

查看:53
本文介绍了我如何要求一个mysql字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现NOT NULL不需要填写字段.

I just discovered NOT NULL does not make a field required.

创建mysql表时,如何创建不能包含null或空白(必须包含某些内容)的字段?

When creating a mysql table, how do I create a field that cannot contain null or blank (must have something in it)?

推荐答案

默认情况下,MySQL接受无效值.您可以将MySQL设置为严格模式以强制使用有效值.这将拒绝不为NOT NULL列提供值的查询,并且对所有类型的列强制实施完整性.

By default, MySQL accepts invalid values. You can set MySQL to strict mode to force valid values. This will reject a query that does not provide a value for a NOT NULL column as well as enforce integrity on all types of columns.

更新:MySQL 5.7和更高版本默认情况下已启用严格模式.因此,默认情况下它不会像以前的版本一样接受无效值.

Update: MySQL 5.7 and above now have strict mode on by default. So it would not accept invalid values by default like previous versions.

http://dev .mysql.com/doc/refman/5.0/en/sql-mode.html#sql-mode-important

http://dev.mysql.com /doc/refman/5.0/zh-CN/sql-mode.html#sqlmode_strict_all_tables

@Barranka和@RocketHazmat在评论中指出了要点. ''与null不同,因此MySQL会在NOT NULL列中允许它.在这种情况下,您将不得不求助于代码或触发器.

@Barranka and @RocketHazmat made good points in the comments. '' is not the same as null, so MySQL will allow that in a NOT NULL column. In that instance, you would have to resort to your code or a trigger.

在代码中(例如PHP),这很容易,运行如下代码:

In the code (PHP for example), this could be easy enough, running something like:

if (!strlen($value)) { 
    // Exclude value or use NULL in query
}

这篇关于我如何要求一个mysql字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆