我需要查找与用户相关的多行,然后插入另一个表或更新当前日记录是否存在。
我这样做
SELECT CASE WHEN
(
SELECT
DISTINCT `userid`,
COUNT(DISTINCT `userip`,`userid`) AS `count`,
@date:=UNIX_TIMESTAMP(CURDATE())
FROM `tablename`
WHERE (`date` >= UNIX_TIMESTAMP(CURDATE())) GROUP BY `userid`
)
THEN
(
UPDATE `tablename2` SET `count`=`count`,`userid`=`userid`,`date`=`date` WHERE `date` >= UNIX_TIMESTAMP(CURDATE()))
)
ELSE
(
INSERT INTO `tablename2` (`count`,`userid`,`date`) VALUES(`count`,`userid`,`date`);
)
END
但这会在UPDATE..
我该如何解决这个问题?
答案 0 :(得分:2)
我猜你想要tablename2
每个用户和日期一行。如果是,请使用唯一索引强制执行此规则:
CREATE UNIQUE INDEX idx_tablename2(userid, date)
然后数据库执行它。
你的SQL很乱,但我想我可以看到你想要做的事情。基本思路是INSERT . . . ON DUPLICATE KEY UPDATE
。我认为以下是您想要的:
INSERT INTO `tablename2` (`count`, `userid`, `date`)
SELECT `userid`, COUNT(DISTINCT `userip`, `userid`) AS `count`,
UNIX_TIMESTAMP(CURDATE())
FROM `tablename`
WHERE `date` >= UNIX_TIMESTAMP(CURDATE())
GROUP BY `userid`
ON DUPLICATE KEY UPDATE `count` = VALUES(`count`);