Question

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 `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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top