在Postgresql中,对两列组合强制唯一

编程入门 行业动态 更新时间:2024-10-20 00:43:16
本文介绍了在Postgresql中,对两列组合强制唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在PostgreSQL中建立一个表,使得两列在一起必须唯一。只要没有两个共享这两个值,就可以有多个值。

例如:

创建表someTable( id int主键自动递增, col1 int非空, col2 int非空)

因此, col1 和 col2 可以重复,但不能同时重复。因此,将允许这样做(不包括ID)

1 1 1 2 2 1 2 2

但不是这样:

1 1 1 2 1 1-会因为违反约束

解决方案

CREATE TABLE someTable( id串行主键, col1 int NOT NULL, col2 int NOT NULL,唯一(col1,col2))

自动增量不是postgresql。您想要一个序列。

如果col1和col2唯一且不能为null,则它们将好主键:

创建表someTable( col1 int NOT NULL, col2 int NOT NULL, 主键(col1,col2))

I would like to set up a table in PostgreSQL such that two columns together must be unique. There can be multiple values of either value, so long as there are not two that share both.

For instance:

CREATE TABLE someTable ( id int PRIMARY KEY AUTOINCREMENT, col1 int NOT NULL, col2 int NOT NULL )

So, col1 and col2 can repeat, but not at the same time. So, this would be allowed (Not including the id)

1 1 1 2 2 1 2 2

but not this:

1 1 1 2 1 1 -- would reject this insert for violating constraints

解决方案

CREATE TABLE someTable ( id serial primary key, col1 int NOT NULL, col2 int NOT NULL, unique (col1, col2) )

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable ( col1 int NOT NULL, col2 int NOT NULL, primary key (col1, col2) )

更多推荐

在Postgresql中,对两列组合强制唯一

本文发布于:2023-10-14 22:09:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492359.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   Postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!