我有两个表,一个名为os_files,包含上传文件的所有信息,还有os_files_downloads,每次下载文件时都会存储一条记录。
我想从os_files中删除自上载以来没有任何下载的记录,或上次下载时间为30天或更早的记录。到目前为止,我有以下代码,但它似乎没有用,有人能指出我正确的方向吗?另外我理解子查询很慢,有更快的方法吗?
SELECT `id`
FROM `os_files`
WHERE `uploadTime` < DATE_SUB(UNIX_TIMESTAMP(NOW()), INTERVAL 30 DAY)
AND `id` NOT IN
(SELECT `fileId`
FROM `os_files_downloads`)
OR `id` IN
(SELECT `fileId`
FROM `os_files_downloads`
WHERE `timestamp` < DATE_SUB(UNIX_TIMESTAMP(NOW()), INTERVAL 30 DAY))
答案 0 :(得分:1)
您只需要删除过去30天内未下载的所有ID。从逻辑上讲,这个集合还将包括从未下载过的任何ID:
SELECT `id`
FROM `os_files`
WHERE `id` NOT IN
(SELECT `id`
FROM `os_files_downloads`
WHERE `timestamp` > DATE_SUB(UNIX_TIMESTAMP(NOW()), INTERVAL 30 DAY))
编辑:
假设os_files_downloads.id
不是外键,那么你需要这个:
SELECT `id`
FROM `os_files`
WHERE `id` NOT IN
(SELECT `os_files_id` --or whatever the foreign key IS called
FROM `os_files_downloads`
WHERE `timestamp` > DATE_SUB(UNIX_TIMESTAMP(NOW()), INTERVAL 30 DAY))
答案 1 :(得分:0)
此处一切正常您只需要通过中的外键替换'id'字段来自子查询 os_files_downloads
,可能 os_files_id
,并且 WHERE
示例:强>
SELECT id
FROM os_files
WHERE (
uploadTime < DATE_SUB(UNIX_TIMESTAMP(NOW()), INTERVAL 30 DAY)
AND id NOT IN
(SELECT os_files_id
FROM os_files_downloads)
)
OR id NOT IN
(SELECT os_files_id
FROM os_files_downloads
WHERE timestamp > DATE_SUB(UNIX_TIMESTAMP(NOW()), INTERVAL 30 DAY))
错误地尝试通过 OR id NOT IN 更改 OR id IN ,并在最后一行 timestamp&lt; DATE_SUB 按时间戳&gt; DATE_SUB 强>
请参阅上面给出的查询
答案 2 :(得分:0)
好的伙计们,在摆弄身边后我终于做到了!答案如下,感谢您的帮助并推动我朝着正确的方向前进!
SELECT id
FROM os_files
WHERE uploadTime < UNIX_TIMESTAMP(NOW() - INTERVAL 30 DAY)
AND id NOT IN (SELECT fileId
FROM os_files_downloads)
OR id NOT IN (SELECT fileId
FROM os_files_downloads
WHERE timestamp > UNIX_TIMESTAMP(NOW() - INTERVAL 30 DAY))