添加一个 INT 列数组,其中每个值都是来自另一个 table 的主键

Adding an Array of INT column where each value is a primary key from another table

给定两个 table 像这样

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[],
);

我希望 'meetings' table 的参与者列包含一组整数,这些整数都是来自 'participants' table.[=12= 的主键(特定参与者) ]

如何在 'meetings' table 中定义此字段?

老式的方法是创建一个 many-many table,有几个常识性约束:

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

现在可以很容易地在会议中添加和删除人员,插入或删除行或查询会议,例如有 4 位或更多参与者。

一种更常见的方法是为会议参与者创建一个连接点 table。

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)
);

然后用于加入 2 tables。
例如:

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