简体   繁体   English

添加 INT 数组类型的列,其中每个 INT 是另一个表的主键(POSTGRES / SQL)

[英]Adding a column of type Array of INT's where each INT is a primary key from another table (POSTGRES / SQL)

Given two tables like so给定两个这样的表

CREATE TABLE participants(
    id SERIAL PRIMARY KEY,
    Name TEXT NOT NULL,
    Title TEXT NOT NULL
);

CREATE TABLE meetings (
    id SERIAL PRIMARY KEY,
    Organizer TEXT NOT NULL,
    StartTime DATE NOT NULL,
    EndTime DATE NOT NULL,
    Participants INT[],
);

I want Participants column of 'meetings' table to contain set of integers which are all primary keys (specific participant) from 'participants' table.我希望“会议”表的参与者列包含一组整数,这些整数都是“参与者”表中的所有主键(特定参与者)。

How do I define this field in 'meetings' table?如何在“会议”表中定义此字段?

The old fashioned way is to create a many-many table, with a couple of commonsense constraints:老式的方法是创建一个多对多表,并带有一些常识性约束:

CREATE TABLE meetings_participants(
    meeting_id int not null,
    participant_id int not null,
    primary key (meeting_id, participant_id),
    constraint fk_meeting_id foreign key(meeting_id) references meetings(id),
    constraint fk_participant_id foreign key(participant_id) references participants(id)
)

Now it is easy to add and remove people to meetings be inserting or deleting rows or query meetings that eg have 4 or more participants.现在很容易在会议中添加和删除人员,例如插入或删除行或查询有 4 个或更多参与者的会议。

A more common approach is to create a junction table for the meeting participants.更常见的方法是为会议参与者创建一个联结表。

CREATE TABLE participants (
  participant_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  Name TEXT NOT NULL,
  Title TEXT NOT NULL
);

CREATE TABLE meetings (
  meeting_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  Organizer TEXT NOT NULL,
  StartTime DATE NOT NULL,
  EndTime DATE NOT NULL
);

CREATE TABLE meeting_participants(
  meeting_id INT NOT NULL, 
  participant_id INT NOT NULL, 
  PRIMARY KEY (meeting_id, participant_id), 
  FOREIGN KEY (meeting_id) REFERENCES meetings(meeting_id), 
  FOREIGN KEY (participant_id) REFERENCES participants(participant_id)
);

Which is then used to join the 2 tables.然后用于连接 2 个表。
For example:例如:

SELECT m.*, p.*
FROM meeting_participants mp
JOIN meetings m USING(meeting_id)
JOIN participants p USING(participant_id)
WHERE m.Organizer = 'John Doe';

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

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