简体   繁体   English

限制列以仅接受2个值

[英]Restricting a column to accept only 2 values

I have a column called "Patient Type" in a table. 我在表格中有一个名为“患者类型”的列。 I want to make sure that only 2 values can be inserted in to the column , either opd or admitted, other than that, all other inputs are not valid. 我想确保只有2个值可以插入到列中,opd或者被允许,除此之外,所有其他输入都无效。

Below is an example of what I want 以下是我想要的一个例子

在此输入图像描述

How do I make sure that the column only accepts "opd" or "admitted" as the data for "Patient Type" column. 如何确保该列仅接受“opd”或“已接纳”作为“患者类型”列的数据。

You need a check constraint. 您需要检查约束。

ALTER TABLE [TableName] ADD CONSTRAINT 
my_constraint CHECK (PatientType = 'Admitted' OR PatientType = 'OPD')

You need to check if it works though in MySQL in particular as of today. 你需要检查它是否适用于MySQL,特别是今天。
Seems it does not work (or at least it did not a few years ago). 似乎它不起作用(或者至少它不是几年前)。

MySQL CHECK Constraint MySQL CHECK约束

CHECK constraint in MySQL is not working MySQL中的CHECK约束不起作用

MySQL CHECK Constraint Workaround MySQL CHECK约束解决方法

Not sure if it's fixed now. 不确定它现在是否已修复。

If not working, use a trigger instead of a check constraint. 如果不起作用,请使用触发器而不是检查约束。

I'm not a MySQL dev, but I think this might be what you're looking for. 我不是MySQL开发者,但我认为这可能是你正在寻找的。 ENUM ENUM

While creating the table use Enum as data type for patientType column. 创建表时,使用Enum作为patientType列的数据类型。 Create table [tablename](firstname varchar(size),[othercolumns],patientType ENUM('OPD','Admitted'))

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

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