gpt4 book ai didi

使用自引用查询更新 mysql

转载 作者:可可西里 更新时间:2023-11-01 07:31:15 24 4
gpt4 key购买 nike

我有一个调查表,其中包含(除其他外)以下列

survey_id  - unique id
user_id - the id of the person the survey relates to
created - datetime
ip_address - of the submission
ip_count - the number of duplicates

由于记录集很大,即时运行此查询是不切实际的,因此尝试创建一个更新语句,定期将“缓存”结果存储在 ip_count 中。

ip_count 的目的是显示在 12 个月(创建日期 +/- 6 个月)内针对同一 user_id 收到的重复 ip_address 调查提交的数量。

使用以下数据集,这是预期的结果。

survey_id   user_id    created    ip_address     ip_count  #counted duplicates survey_id
1 1 01-Jan-12 123.132.123 1 # 2
2 1 01-Apr-12 123.132.123 2 # 1, 3
3 2 01-Jul-12 123.132.123 0 #
4 1 01-Aug-12 123.132.123 3 # 2, 6
6 1 01-Dec-12 123.132.123 1 # 4

这是迄今为止我想出的最接近的解决方案,但是这个查询没有考虑到日期限制并且很难找到替代方法。

UPDATE surveys
JOIN(
SELECT ip_address, created, user_id, COUNT(*) AS total
FROM surveys
WHERE surveys.state IN (1, 3) # survey is marked as completed and confirmed
GROUP BY ip_address, user_id
) AS ipCount
ON (
ipCount.ip_address = surveys.ip_address
AND ipCount.user_id = surveys.user_id
AND ipCount.created BETWEEN (surveys.created - INTERVAL 6 MONTH) AND (surveys.created + INTERVAL 6 MONTH)
)
SET surveys.ip_count = ipCount.total - 1 # minus 1 as this query will match on its own id.
WHERE surveys.ip_address IS NOT NULL # ignore surveys where we have no ip_address

提前感谢您的帮助:)

最佳答案

对上面显示的内容进行一些(非常)小的调整。再次感谢!

UPDATE surveys AS s
INNER JOIN (
SELECT x, count(*) c
FROM (
SELECT s1.id AS x, s2.id AS y
FROM surveys AS s1, surveys AS s2
WHERE s1.state IN (1, 3) # completed and verified
AND s1.id != s2.id # dont self join
AND s1.ip_address != "" AND s1.ip_address IS NOT NULL # not interested in blank entries
AND s1.ip_address = s2.ip_address
AND (s2.created BETWEEN (s1.created - INTERVAL 6 MONTH) AND (s1.created + INTERVAL 6 MONTH))
AND s1.user_id = s2.user_id # where completed for the same user
) AS ipCount
GROUP BY x
) n on s.id = n.x
SET s.ip_count = n.c

关于使用自引用查询更新 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9939172/

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