sql - 在 Sequelize 中使每个用户 ID 的字段唯一?

标签 sql database postgresql sequelize.js unique-constraint

场景:

用户有 3 个选择,第 1 个选择,第 2 个选择,第 3 个选择。每个选择都保存在数据库中,并带有选择号和用户 ID。

如何进行唯一验证,使用户#11 不能有两个选择#2。

阅读文档,您似乎只能输入一栏,例如电子邮件。

最佳答案

这是你想要的吗?

CREATE UNIQUE INDEX idxu_user_choice ON my_table(choice_id, user_id);

SQL Fiddle

PostgreSQL 9.6 架构设置:

CREATE TABLE t
    ("user_id" int, "choice_id" int, "comment" varchar(8))
;
CREATE UNIQUE INDEX idxu_user_choice ON t(choice_id, user_id);

INSERT INTO t
    ("user_id", "choice_id", "comment")
VALUES
    (1, 1, 'azer'),
    (1, 2, 'zsdsfsdf'),
    (2, 1, 'sdghlk')
;

查询 1:

INSERT INTO t ("user_id", "choice_id", "comment")
VALUES (2, 2, 'dfgdfgh')

Results : 查询 2:

select * from t

Results :

| user_id | choice_id |  comment |
|---------|-----------|----------|
|       1 |         1 |     azer |
|       1 |         2 | zsdsfsdf |
|       2 |         1 |   sdghlk |
|       2 |         2 |  dfgdfgh |

查询 3:

INSERT INTO t ("user_id", "choice_id", "comment")
VALUES (1, 2, 'cvbkll')

Results :

ERROR: duplicate key value violates unique constraint "idxu_user_choice" Detail: Key (choice_id, user_id)=(2, 1) already exists.

关于sql - 在 Sequelize 中使每个用户 ID 的字段唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092842/

相关文章:

mysql - 具有复杂 'if/else' 要求的 SQL SELECT 语句

SQL:将整行数据与数字进行比较

sql - 如何使 SQL Server 中的两个 3 列唯一?

database - 如何在查询中同时使用 LIKE 和 OR

python - 对 SQLAlchemy 中的 UniqueKeyViolation 使用react

sql - 将日期添加到 SQL 数据库备份文件名

java - 将整数值添加到数据库表错误

python - Python中的内存数据库

php - Postgresql 选择您可能认识的人,按共同 friend 的数量排序

postgresql - 将 Google Compute Engine 连接到 Cloud SQL