gpt4 book ai didi

mysql - 为什么当值不存在时不添加新行?

转载 作者:行者123 更新时间:2023-11-29 17:19:31 25 4
gpt4 key购买 nike

我有一个用于计算观看次数的表格:

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

其中post_idposts表的id相关:

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

来自 posts 的每个 id 都应该在 post_views 表中占据一行,因此 id 是主要的 View 表和 post_id 是唯一的。

如果 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

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

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

最佳答案

您尚未将 id 声明为 auto_increment。您的表声明应如下所示:

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

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

您可能已指定idnot null(或主键),默认值为0 。对于所有插入都是如此,因此所有尝试的插入都具有相同的值。 auto_increment 应该可以解决这个问题。

关于mysql - 为什么当值不存在时不添加新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51340979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com