Hi everyone,
I have a MySQL query to get items that have had recent activity. Basically users can post a review or add it to their wishlist, and I want to get all items that have either had a new review in the last x days, or was placed on someone's wishlist.
The query goes a bit like this (slightly simplified):
SELECT items.*, reaction.timestamp AS date FROM items
LEFT JOIN reactions ON reactions.item_id = items.id
WHERE reactions.timestamp > 1251806994
GROUP BY items.id
UNION
SELECT items.*, wishlists.timestamp AS date FROM items
LEFT JOIN wishlist ON wishlists.item_id = items.id
WHERE wishlists.timestamp > 1251806994
GROUP BY items.id
ORDER BY date DESC LIMIT 5
This works, but when an item has been placed both on someone's wishlist and a review was posted, the item is returned twice. UNION
removes duplicates normally, but because the date
differs between the two rows, both rows are returned. Can I somehow tell MySQL to ignore the date when removing duplicate rows?
I also tried doing something like this:
SELECT items.*, IF(wishlists.id IS NOT NULL, wishlists.timestamp, reactions.timestamp) AS date FROM items
LEFT JOIN reactions ON reactions.item_id = items.id
LEFT JOIN wishlist ON wishlists.item_id = items.id
WHERE (wishlists.id IS NOT NULL AND wishlists.timestamp > 1251806994) OR
(reactions.id IS NOT NULL AND reactions.timestamp > 1251806994)
GROUP BY items.id
ORDER BY date DESC LIMIT 5
But that turned out to be insanely slow for some reason (took about half a minute).