如果值不存在,为什么不添加新行?

时间:2018-07-14 15:47:33

标签: mysql sql

我有一张用于统计观看次数的表格:

             post_views table
    ___________________________________
   |        |             |           |
   |   id   |   post_id   |   views   |
   |________|_____________|___________|

post_idid表的posts相关的地方:

               posts table
    __________________________________________
   |        |           |          |         |
   |   id   |   title   |   text   |    ..   |
   |________|___________|__________|_________|

id中的每个postspost_views表中应该有一行,因此id在视图表中是主要的,而post_id是唯一的。 / p>

如果存在views,我想增加post_id的数量,否则插入新的post_id

所以我正在使用该查询:

INSERT INTO post_views (`post_id`, `views`) VALUES (1, 1) ON DUPLICATE KEY UPDATE `views` = `views`+1

这创建了id = 0的新行:

____________________________________
|          |             |           |
|    id    |   post_id   |   views   |
|__________|_____________|___________|
|          |             |           |
|    0     |     1       |    1      |
|          |             |           |
|__________|_____________|___________|

每当我使用新的post_id运行相同的查询时:

INSERT INTO post_views (`post_id`, `views`) VALUES (2, 1) ON DUPLICATE KEY UPDATE `views` = `views`+1

现有同一行中的视图增加,并且未添加新的post_id

 ____________________________________
|          |             |           |
|    id    |   post_id   |   views   |
|__________|_____________|___________|
|          |             |           |
|    0     |     1       |    2      |
|          |             |           |
|__________|_____________|___________|

1 个答案:

答案 0 :(得分:1)

您尚未声明idauto_increment。您的表声明应类似于:

create table post_views (
    id int auto_increment primary key,
    post_id int not null,
    . . . 
);

当您将id留在插入内容之外时,它将获得默认值。对于auto_increment,默认值为递增的id

您可能已指定idnot null(或primary key),默认值为0。所有插入均如此,因此所有尝试插入的值均相同。 auto_increment应该可以解决此问题。

相关问题