today my SQl problem is how to limit some query results based on a user quota.
here is the use case :
- a user owns 1...N websites which have 1...N webpages
- a user has a scan_quota which allow him (or not) to visit his webpages
users
+-----+------------+
| id  | scan_quota |
+-----+------------+
|   1 |          0 |
|   2 |         10 |
|   3 |         20 |
+-----+------------+
websites
+-----+---------+------------------------------------------------+
| id  | user_id | url                                            |
+-----+---------+------------------------------------------------+
|   1 |       1 | http://www.site1.com                           |
|   2 |       2 | http://www.site2.com                           |
|   3 |       3 | http://www.site3.com                           |
+-----+---------+------------------------------------------------+
webpages
+-------+------------+--------------------------------------+---------------------+
| id    | website_id | url                                  | last_scan_date      |
+-------+------------+--------------------------------------+---------------------+
| 1     |          1 | http://wwww.site1.com/page1          | 2015-07-02 21:00:56 |
| 2     |          2 | http://wwww.site2.com/page1          | 2015-07-02 21:01:36 |
| 3     |          3 | http://wwww.site3.com/page1          | 2015-07-02 21:00:32 |
+-------+------------+--------------------------------------+---------------------+
Every week I want to get a list of webpages urls who have to be scanned based on user scan_quota.
With this simple query, I can get ALL pages :
SELECT us.id, ws.user_id, wp.id, wp.website_id, wp.url 
FROM users us, webpages wp, websites ws 
  WHERE us.id = ws.user_id 
    AND wp.last_scan_date < '2015-10-08' 
    AND ws.id = wp.website_id 
  ORDER BY wp.website_id ASC;
But as soon as I want to limit results based on user scan_quota I get lost because a global LIMIT won't acheive what I want and I don't know how I could use JOIN (INNER or LEFT) to reach my goal.
I've created a SQL Fiddle to play easily with my use case.
Thanks for your suggestions and help !
SOLUTION NOT OPTIMIZED
In a first query I extract user id and scan quota and then loop over them to build my final query using union all (which allows to use a LIMIT per user):
$query .= "(SELECT ws.user_id, wp.id, wp.website_id, wp.url FROM webpages wp, websites ws WHERE ws.user_id = ".$user_id." 
                    AND wp.last_scan_date < '2015-10-08' 
                    AND ws.id = wp.website_id LIMIT ".$scan_pages.") union all ";
If you have a way to group those 2 queries in one or an optimized one, let's share.
I'm also trying to use variables and sub queries (like i this example : https://stackoverflow.com/a/13187418/2295192) but with no luck for now ...
 
     
    