gpt4 book ai didi

mysql - SQL更新忽略重复项

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

我有 2 个表,table_a 和 table_b,创建和填充如下:

DROP TABLE IF EXISTS `table_a`;
CREATE TABLE `table_a` (
`a_id` bigint(20) NOT NULL auto_increment,
`user_name` varchar(255) default NULL,
`created_at` datetime default NULL,
`running_count` int default NULL,
PRIMARY KEY (`a_id`)
);

DROP TABLE IF EXISTS `table_b`;
CREATE TABLE `table_b` (
`b_id` bigint(20) NOT NULL auto_increment,
`user_name` varchar(255) default NULL,
`start` datetime default NULL,
`end` datetime default NULL,
`total_count` int default NULL,
PRIMARY KEY (`b_id`)
);

insert into table_a values (NULL, '1', '2013-07-05 01:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 02:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 02:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 03:00:00', 2);
insert into table_a values (NULL, '1', '2013-07-05 07:00:00', 1);
insert into table_a values (NULL, '1', '2013-07-05 08:00:00', 1);

insert into table_b values (NULL, '1', '2013-07-05 00:00:00', '2013-07-05 06:00:00', 0);
insert into table_b values (NULL, '1', '2013-07-05 06:00:01', '2013-07-05 12:00:00', 0);

下面的查询用总计数更新 table_b:

update table_b b
set
total_count=
(
SELECT IFNULL(SUM(a.running_count),0) total_count
FROM table_a a
where a.created_at BETWEEN b.start and b.end
and a.user_name=b.user_name
and a.created_at between '2013-07-05 00:00:00' and '2013-07-05 23:59:59'
);

结果不错:

+------+-----------+---------------------+---------------------+-------------+
| b_id | user_name | start | end | total_count |
+------+-----------+---------------------+---------------------+-------------+
| 1 | 1 | 2013-07-05 00:00:00 | 2013-07-05 06:00:00 | 5 |
| 2 | 1 | 2013-07-05 06:00:01 | 2013-07-05 12:00:00 | 2 |
+------+-----------+---------------------+---------------------+-------------+

但我需要第一个计数是 4 而不是 5,因为在 2013-07-05 02:00:00 有一条重复记录,应该计数为 1 而不是 2。

如果有多个重复的时间戳,我如何修改更新查询只计数 1?

最佳答案

替换:

FROM    table_a a

与:

FROM   (
SELECT DISTINCT created_at
, user_name
, running_count
FROM table_a
) a

关于mysql - SQL更新忽略重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17478360/

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