在 MySQL 中以 false 作为默认值创建布尔列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2221069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:13:38  来源:igfitidea点击:

Create boolean column in MySQL with false as default value?

mysql

提问by user169258

I want to create a table in MySQL with a booleancolumn whose default value is false. But it's accepting NULL as default...

我想在 MySQL 中创建一个表,boolean其默认值为false. 但它接受 NULL 作为默认值...

回答by Asaph

You have to specify 0(meaning false) or 1(meaning true) as the default. Here is an example:

您必须指定0(意味着 false) 或1(意味着 true) 作为默认值。下面是一个例子:

create table mytable (
     mybool boolean not null default 0
);

FYI: booleanis an alias for tinyint(1).

仅供参考:booleantinyint(1).

Here is the proof:

这是证据:

mysql> create table mytable (
    ->          mybool boolean not null default 0
    ->     );
Query OK, 0 rows affected (0.35 sec)

mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from mytable;
+--------+
| mybool |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

FYI: My test was done on the following version of MySQL:

仅供参考:我的测试是在以下版本的 MySQL 上完成的:

mysql> select version();
+----------------+
| version()      |
+----------------+
| 5.0.18-max-log |
+----------------+
1 row in set (0.00 sec)

回答by Gaurav Sethi

Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.

在 MySQL 中使用 ENUM 表示真/假,它给出并接受真/假值,无需任何额外代码。

ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'

回答by Archana Shah

You can set a default value at creation time like:

您可以在创建时设置默认值,例如:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
Married boolean DEFAULT false);