insert,如果存在则使用trigger更新

时间:2015-11-19 14:03:18

标签: mysql triggers on-duplicate-key

我想为我的网站实施一个被查看的系统。这是我的表的结构:

// 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

现在,在table2中插入后,我需要触发插入/更新table1

我 我想我必须使用on duplicate key

1 个答案:

答案 0 :(得分:1)

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

使用以下2个示例表: -

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

您可以使用表1中的以下触发器来计算计数并将其插入表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

另请注意,使用table1中post_id的索引来获取计数的子查询将更有效