开发者

How can I create a table with a column with 3 only possible given values?

I'm making a SQL database with MySQL.

I need a column th开发者_StackOverflow中文版at has only 3 possible values: "Total" "Hours" "OnDemmand". I mean that user has to select one of these three values, he will can't select another value.

How can I do it?


See the ENUM type. http://dev.mysql.com/doc/refman/5.0/en/enum.html

i.e.

CREATE TABLE sizes (
    name ENUM('small', 'medium', 'large')
);


In Oracle, you can create a check constraint for the column like this -

ALTER TABLE yourtable
add CONSTRAINT yourcolumn
   CHECK (yourcolumn IN ('Total', 'Hours', 'OnDemand'));

There should be equivalent checks incase you are using other database.


If you want to build it into the table itself you would need to use a check constraint, like so:

CREATE TABLE YourTable
(
  YourColumn VARCHAR(50) NOT NULL,
  CONSTRAINT ck_YourConstraint CHECK (YourColumn = 'Total' OR YourColumn = 'Hours' OR YourColumn = 'OnDemand')
)

However, you may want to look into normalizing your database design a step further and putting those into a separate lookup table that your application uses. This will allow you great flexibility in the future in the event that those lookups are modified in any way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜