php - 什么数据类型可用于在mysql中放置标志(布尔值)?

原文 标签 php mysql sql database

What data type can be used to put a flag (boolean) in mysql?

I have a database in which I have the following columns:

emp_id: INT(11) (PRIMARY KEY)
FirstName: varchar(45)
LastName: varchar(45)
password: varchar(45)
admin: ????

I want the admin column to be a flag, so the employee is either an admin (true) or not an admin (false). Can someone please tell me what datatype to assign to this column in the mysql table?

Answer

You should be able to declare the column as TINYINT NOT NULL DEFAULT FALSE (or DEFAULT 0).

An insert would be VALUES (TRUE, ... or VALUES (FALSE, ... or VALUES(1, ... or VALUES (0, ....

As an unquoted literal, TRUE is equivalent to 1 and FALSE is equivalent to 0, because there is no pure Boolean data type in MySQL.

Your application will always see the column as containing 1 or 0 in result sets.

Disregard the number in parentheses, e.g. TINYINT(1) or TINYINT(4). That's part of a legacy feature that provided hints to applications for how wide the value stored in a column would be expected to be... it was useful for fixed-width fonts on display terminals, but is largely ignored by applications today, and this value changes nothing about the contents of the column or the storage requirements for it. A TINYINT requires 1 byte of storage per row.

Using an ENUM isn't typically recommended for the boolean case, because behind the curtain, enums have numeric values that can cause logical ambiguities, since the "string" for a value will be cast implicitly to it's integer index (1-based, not 0-based) in some contexts.

翻译

我有一个数据库,其中包含以下各列:

emp_id: INT(11) (PRIMARY KEY)
FirstName: varchar(45)
LastName: varchar(45)
password: varchar(45)
admin: ????


我希望admin列是一个标志,因此员工是admin(true)或不是admin(false)。有人可以告诉我要分配给mysql表中此列的数据类型吗?
最佳答案
您应该能够将该列声明为TINYINT NOT NULL DEFAULT FALSE(或DEFAULT 0)。

插入将是VALUES (TRUE, ...VALUES (FALSE, ...VALUES(1, ...VALUES (0, ...

作为无引号文字,TRUE等于1,FALSE等于0,因为MySQL中没有纯布尔数据类型。

您的应用程序将始终在结果集中看到该列包含1或0。

忽略括号中的数字,例如TINYINT(1)TINYINT(4)。这是一项传统功能的一部分,该功能向应用程序提供提示,以了解存储在列中的值应该有多宽...对于显示终端上的固定宽度字体很有用,但今天被应用程序很大程度上忽略了这一点。值不会改变列的内容或存储要求。 TINYINT每行需要1字节的存储空间。

对于布尔型情况,通常不建议使用ENUM,因为在幕后,枚举具有会引起逻辑歧义的数值,因为值的“字符串”将隐式转换为其整数索引(从1开始,而不是从0开始)。
相关推荐

javascript - 尝试将数据从.php文件传递到.js文件

php - 更改子菜单时如何更改网页背景?

php - Symfony2:如何避免数据库中已经存在重复的实体?

php - Eclipse中的PHP 7调试器设置

javascript - 访问URL参数-PHP和Angular.js

php - 使用更新的MySQL库修复PHP数据库连接失败

php - PHP代码不允许多个输入值通过我的表单发送

php - Laravel 5.1内部联接查询中的问题

php - 控制PHP ldap分页-结果数和页码

php - 带有PHPStorm 10的PHP7