我有一张这样的表:
CREATE TABLE `UserTmp` (
`user_id` bigint(20) unsigned NOT NULL,
`nb_invit` bigint(20) unsigned DEFAULT '0',
`nb_share` bigint(20) unsigned DEFAULT '0',
`nb_sent` bigint(20) unsigned DEFAULT '0',
`total` bigint(20) unsigned DEFAULT '0',
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
我想执行这样的3个查询(每个表一个,以便有nb_share,nb_invit和nb_sent):
INSERT INTO UserTmp (user_id, nb_share)
select user_id, count(share_date) as 'nb_share'
from Share
where share_date between '2012-05-21 00:00:00' and '2012-05-28 00:00:00'
ON DUPLICATE KEY UPDATE nb_share=VALUES(nb_share);
使用nb_share字段的等于表中存在的当前用户的份额数,并且需要更新
目标是让用户列表中包含操作数量和总字段,这是用户完成的操作的总和。
VALUES(nb_share)接缝向我提供所有用户的nb_share总数,而不是当前用户。
你有想法解决这个问题吗?
由于
答案 0 :(得分:3)
您需要将SELECT
分组为user_id
:
INSERT INTO UserTmp (user_id, nb_share)
SELECT user_id, count(share_date)
FROM Share
WHERE share_date BETWEEN '2012-05-21 00:00:00' AND '2012-05-28 00:00:00'
GROUP BY user_id
ON DUPLICATE KEY UPDATE nb_share = VALUES(nb_share)
答案 1 :(得分:0)
或者您可以使用用户定义的变量:
INSERT INTO UserTmp (user_id, nb_share)
SELECT user_id, @nbshare := count(share_date)
FROM Share
WHERE share_date BETWEEN '2012-05-21 00:00:00' AND '2012-05-28 00:00:00'
GROUP BY user_id
ON DUPLICATE KEY UPDATE nb_share = @nbshare