I've got a query that's messing with my head. I usually try to avoid using IN() lists, but I can't think of how to rewrite this query to avoid it. Hopefully someone can help me correctly aggregate this query.
In my doc management system, I track "owners" (the person who uploaded a document) and revisors - which may be the same or different users. I also track upload dates and revision dates. I need to get a count of documents uploaded or revised in the last 30 days by the user's location_id (in the Users table).
This query works but it seems like very bad form:
foreach($loc_id as $location_id)
{
$query = "SELECT COUNT(doc_id) AS doc_count FROM Documents WHERE
(
upload_date > CURDATE() - INTERVAL 30 DAY OR rev_date > CURDATE() - INTERVAL 30 DAY
)
AND
(
owner_id IN (SELECT user_id FROM Users WHERE location_id = $location_id) OR
rev_id IN (SELECT user_id FROM Users WHERE location_id = $location_id)
)";
// Output, etc...
}
Can someone suggest a better way to write this?