简体   繁体   English

MySQL:唯一分组

[英]MySQL: Unique grouped

I have a problem while designing my database and I don't know how to solve it: 我在设计数据库时遇到问题,我不知道如何解决它:

i have following table (relevant columns): 我有下表(相关专栏):

CREATE TABLE IF NOT EXISTS `prmgmt_tasks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(300) NOT NULL,
  `project_id` int(11) NOT NULL,
);

What I want: every task has a unique id (autoincrement). 我想要的是:每个任务都有一个唯一的id(自动增量)。 The name of the task is not unique, but it should be unique for each project. 任务的名称不是唯一的,但对于每个项目它应该是唯一的。 For example "Design userinterface" can occur in project with id 1 and 2, but not twice in project with id 1. Something like 'unique for: group by project_id'. 例如,“设计用户界面”可以在ID为1和2的项目中出现,但在项目中为id 1时不会出现两次。类似于'unique for:group by project_id'。

Of course, I could check that in every query, but I am looking for a way to model this in the database, so it will allways be consistent, no matter what queries are executed. 当然,我可以在每个查询中检查它,但我正在寻找一种在数据库中对此进行建模的方法,因此无论执行什么查询,它都将始终保持一致。

Thanks for help! 感谢帮助!

Create a unique composite index on the combined fields. 在组合字段上创建唯一的复合索引。

CREATE UNIQUE INDEX tasks_name_project
ON prmgmt_tasks (name, project_id);

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

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