插入,如果存在使用触发器更新

insert, if exist update using trigger

我想为我的网站实施 Viewed 系统。这是我的表的结构:

// table1
id | user_or_ip | post_id | date_time   // inserting new row for each viewed

// table2
id | post_id | total_viewed             // getting the number of total viewed for each post

现在我需要在插入 table1 后触发 insert/update table2

我 我想我必须使用 on duplicate key.

你可以很容易地做到这一点。

以下面2个例子table:-

CREATE TABLE table1
(
    id  INT NOT NULL AUTO_INCREMENT,
    user_or_ip  VARCHAR(255),
    post_id INT,
    date_time   DATETIME,
    PRIMARY KEY (id)
);

CREATE TABLE table2
(
    id  INT NOT NULL AUTO_INCREMENT,
    post_id INT,
    total_viewed    INT,
    PRIMARY KEY (id),
    UNIQUE KEY post_id (post_id)
);

您可以在 table 1 上使用以下触发器来计算计数并将其插入到 table 2:-

CREATE TRIGGER `trig_1` AFTER INSERT ON `table1`
 FOR EACH ROW BEGIN
INSERT INTO table2(post_id, total_viewed) 
SELECT post_id, COUNT(*)
FROM table1
WHERE post_id = NEW.post_id
GROUP BY post_id
ON DUPLICATE KEY UPDATE total_viewed = VALUES(total_viewed);
END

请注意,如果您确定永远不会出现错误,则可以在 ON DUPLICATE KEY 子句中插入计数 1 并将其设置为 total_count + 1。但是,如果任何阻止触发的失败,计数将永远是错误的 post_id:-

CREATE TRIGGER `trig_1` AFTER INSERT ON `table1`
 FOR EACH ROW BEGIN
INSERT INTO table2(post_id, total_viewed) 
VALUES(NEW.post_id, 1)
ON DUPLICATE KEY UPDATE total_viewed = total_viewed + 1;
END

另请注意,使用 post_id in table1

上的索引获取计数的子查询会更高效