Home >Database >Mysql Tutorial >How to define the data type of gender field in MySQL?

How to define the data type of gender field in MySQL?

PHPz
PHPzOriginal
2024-03-14 13:00:05911browse

How to define the data type of gender field in MySQL?

Generally, the ENUM type can be used to define the data type of the gender field in MySQL. The ENUM type can limit the value of a field to a specified list of values, thus ensuring that only predefined values ​​can be stored.

The following is a sample code that demonstrates how to define a table containing gender information in MySQL and set the data type of the gender field to the ENUM type:

-- 创建包含性别信息的表
CREATE TABLE user (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    gender ENUM('男', '女', '未知') -- 定义性别字段为ENUM类型,只能存储'男'、'女'和'未知'三种值中的一个
);

-- 插入数据
INSERT INTO user (id, name, gender) VALUES (1, '张三', '男');
INSERT INTO user (id, name, gender) VALUES (2, '李四', '女');
INSERT INTO user (id, name, gender) VALUES (3, '王五', '未知');

-- 查询数据
SELECT * FROM user;

In the above code, For the gender field gender, we set its data type to ENUM ('male', 'female', 'unknown'), so that only one of these three values ​​can be selected when inserting data. At the same time, we created a user table containing the id, name and gender fields, and inserted three pieces of data respectively. Finally, query the data through the SELECT statement to verify that the data is successfully inserted.

Through the above code example, we can clearly understand how to define the data type of the gender field in MySQL and use the ENUM type to limit the range of field values.

The above is the detailed content of How to define the data type of gender field in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn