有没有办法将PostgreSQL列定义为枚举?

发布于 2025-02-12 21:48:17 字数 259 浏览 0 评论 0原文

在PostgreSQL DB中,想象一下您要添加一个称为warter_type的列,并且您只希望以下3个条目之一出现:cartruck /code>,或摩托车。我认为可以以某种方式定义这个方法,但是请尝试我可能会阅读很多文章,我不知道该怎么做。

注意:我正在与DBEAVER客户端合作,但也可以运行任何SQL命令。

有办法吗?

In a PostgreSQL DB, imagine you want to add a column called vehicle_type and you only want one of the following 3 entries to ever possibly appear: car, truck, or motorcycle. I thought there would be a way to define this somehow but try a I might, and reading lots of articles, I couldn't figure out how to do it.

Note: I'm working with the DBeaver client but also can run any SQL commands too.

Is there a way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蹲在坟头点根烟 2025-02-19 21:48:17
CREATE TYPE vehicle_type AS ENUM ('car', 'truck', 'motorcycle');
-- add column with default
ALTER TABLE tbl ADD COLUMN v_type vehicle_type NOT NULL DEFAULT 'car';

在此处阅读手册。

em>“您只希望以下3个条目之一出现” ,也不会使其无效。

枚举占据4个字节。 To keep the disk footprint to a minimum, you could alternatively use a

ALTER TABLE tbl
  ADD column v_type2 "char" NOT NULL DEFAULT 'c'
, ADD CONSTRAINT v_type_allowed CHECK (v_type2 IN ('c', 't', 'm'));

效力:小,快速。
缺点:特定于Postgres的,不那么可读。

db<>

;

  • gt href =“ https://dba.stackexchange.com/a/166167/3684”>单字节“ char”类型在PostgreSQL中如何工作?
CREATE TYPE vehicle_type AS ENUM ('car', 'truck', 'motorcycle');
-- add column with default
ALTER TABLE tbl ADD COLUMN v_type vehicle_type NOT NULL DEFAULT 'car';

Read the manual here.

Since " you only want one of the following 3 entries to ever possibly appear", also make it NOT NULL.

An enum occupies 4 bytes. To keep the disk footprint to a minimum, you could alternatively use a "char" field instead which occupies 1 byte;

ALTER TABLE tbl
  ADD column v_type2 "char" NOT NULL DEFAULT 'c'
, ADD CONSTRAINT v_type_allowed CHECK (v_type2 IN ('c', 't', 'm'));

Upsides: small, fast.
Downsides: Postgres-specific, less readable.

db<>fiddle here

See:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文