维护/更新关联集

时间:2017-06-15 11:07:08

标签: php mysql mysqli

假设我们有这些表:

CREATE TABLE meetings (
    id INT AUTO_INCREMENT,
    # other fields
    PRIMARY KEY(id)
);
CREATE TABLE participants (
    id INT AUTO_INCREMENT,
    # other fields
    PRIMARY KEY(id)
);
CREATE TABLE meetings_participations (
    meeting INT,      # for joining on meetings.id
    participant INT,  # for joining on participants.id
    PRIMARY KEY(meeting,participant)
);

鉴于该会议中参与者的特定$meeting_id和数组$participant_ids,更新表meetings_participations的好方法是什么?

我考虑过

DELETE FROM meetings_participations
    WHERE meeting = $meeting_id;
INSERT INTO meetings_participations
        (meeting, participant)
    VALUES
        $participations;

其中,在PHP中

$participations = join(',', array_map(function($p){
    return "($meeting_id,$p)";
}, $participant_ids));

但我想知道尝试保存现有记录(而不是无条件地删除并重新插入)是否更好。是否有更好的解决一般问题的方法?

0 个答案:

没有答案