开发者

Deleting unneeded rows from a table with 2 criteria

开发者 https://www.devze.com 2023-02-02 09:50 出处:网络
I have a many-to-many relations table and I need to DELETE the unneeded rows. The lastviews table\'s structure is:

I have a many-to-many relations table and I need to DELETE the unneeded rows. The lastviews table's structure is:

| user (int) | document (int) | time (datetime) |

This table logs the last users which viewed the document. (user, document) is unique. I show only the last 10 views of a document and until now I deleted the unneeded like this:

DELETE FROM `lastviews` WHERE `document` = ? AND `user` NOT IN (SELECT * FROM (SELECT `user` FROM `lastviews` WHERE `document` = ? ORDER BY `time` DESC LIMIT 10) AS TAB)

However, now I need to also show the last 5 documents a user has viewed. This means I can no longer delete rows using the previous query because it might delete information I need (say a user didn't view documents in 5 minutes and the rows are deleted)

To sum up, I need to delete all the records that aren't in the results of these 2 queries:

SELECT ... FROM开发者_如何学JAVA `lastviews` WHERE `document` = ? ORDER BY `time` DESC LIMIT 10

and

SELECT * FROM `lastviews` WHERE `user` = ? ORDER BY `time` DESC LIMIT 0, 5

I need the logic.


can an OR in your query resolve your issue?

something like this:

DELETE FROM `lastviews` WHERE `document` = ? AND (`user` NOT IN (SELECT * FROM (SELECT `user` FROM `lastviews` WHERE `document` = ? ORDER BY `time` DESC LIMIT 10) AS TAB) OR 'user' NOT IN (SELECT * FROM (SELECT 'user' FROM `lastviews` WHERE `user` = ? ORDER BY `time` DESC LIMIT 0, 5) AS TAB))

so it should delete only the records that aren't contained in the two SELECT that you need


I'm closing this question. I didn't find the answer I was looking for but ended doing it another way. I decided to remove these records that are 2 days old so there won't be any unused rows in the database.

0

精彩评论

暂无评论...
验证码 换一张
取 消