0

I just want to update automatically a column of 2 tables linked with foreign keys. To more, these columns have to contain not just one value, but a list of values.

Here is my example :

Table Name : members
Member name : Demo User
Assigned Tasks : <List of tasks assigned to "Demo User">

Table Name : tasks
Task Name : Modeling
Assigned To : <List of users assigned to "Modeling">

In each table, I want to be able to insert value in the column, and the other table is automatically updated.

Example :

Table Name : members
Member name : Demo User
Assigned Tasks : Modeling,Mapping

Table Name : tasks
Task Name : Modeling
Assigned To : AUTOMATIC UPDATE ->Demo User

Task Name : Mapping
Assigned To : AUTOMATIC UPDATE ->Demo User

I tried with foreign keys (using innoDB), but I just succeed to insert one value in the column, and the other table was not updated automatically...

Thank you for your help !

4

1 回答 1

0

永远不要在数据库中存储分隔值。通过创建一个多对多表(在您的情况下我们称之为assigned_tasks)来规范化您的数据。从长远来看,它将使您能够正常维护和查询数据,从而获得巨大的回报。

话虽如此,您的架构可能看起来像

CREATE TABLE members
(
  member_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
  member_name VARCHAR(32)
);
CREATE TABLE tasks
(
  task_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
  task_name VARCHAR(32)
);
CREATE TABLE assigned_tasks
(
  member_id int, 
  task_id int,
  PRIMARY KEY (member_id, task_id),
  FOREIGN KEY (member_id) REFERENCES members (member_id),
  FOREIGN KEY (task_id)   REFERENCES tasks (task_id)
);

现在,如果您需要一个带有每个用户的分隔任务列表的表示,您可以使用GROUP_CONCAT()GROUP BY

SELECT m.member_id, m.member_name, GROUP_CONCAT(t.task_name) tasks
  FROM assigned_tasks a JOIN members m
    ON a.member_id = m.member_id JOIN tasks t
    ON a.task_id = t.task_id
 GROUP BY m.member_id, m.member_name

输出:

| 会员ID | 会员名 | 任务 |
|-----------|-------------|------------------|
| 1 | 演示用户 | 建模、测绘 |

这是SQLFiddle演示

于 2013-11-03T14:14:50.617 回答