Dette er alle oversigter for denne måned for alle restauranter, der er gratis i dag:
SELECT r.`id`, r.`name`, o.`date`, o.`status`, o.`id` order_id
FROM restaurants r
INNER JOIN orders o
ON r.id = o.restaurant_id
LEFT JOIN
( SELECT DISTINCT o2.Restaurant_ID
FROM orders o2
WHERE o2.date = DATE(CURRENT_TIMESTAMP)
) o2
ON r.id = o2.restaurant_id
WHERE o.Date >= DATE_FORMAT(CURRENT_TIMESTAMP ,'%Y-%m-01')
AND o.Date <= DATE_FORMAT(DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) ,'%Y-%m-01')
AND o2.Restaurant_ID IS NULL;
Dette får simpelthen alle restauranter med reservationer i dag (underforespørgsel o2), og ekskluderer derefter disse restauranter:
AND o2.Restaurant_ID IS NULL;
Dette er alle fortegnelser for denne måned for alle restauranter, der har mindst én gratis dag i denne måned:
SELECT r.`id`, r.`name`, o.`date`, o.`status`, o.`id` order_id
FROM restaurants r
INNER JOIN orders o
ON r.id = o.restaurant_id
AND o.date BETWEEN '2013-08-10' AND '2013-08-31'
INNER JOIN
( SELECT o2.Restaurant_ID
FROM orders o2
WHERE o2.Date >= DATE_FORMAT(CURRENT_TIMESTAMP ,'%Y-%m-01')
AND o2.Date <= DATE_FORMAT(DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) ,'%Y-%m-01')
GROUP BY o2.Restaurant_ID
HAVING COUNT(DISTINCT o2.Date) < DAY(DATE_ADD(DATE_FORMAT(DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) ,'%Y-%m-01'), INTERVAL -1 DAY))
) o2
ON r.id = o2.restaurant_id
WHERE o.Date >= DATE_FORMAT(CURRENT_TIMESTAMP ,'%Y-%m-01')
AND o.Date <= DATE_FORMAT(DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) ,'%Y-%m-01');
Tricket er at få antallet af dage i denne måned:
DAY(DATE_ADD(DATE_FORMAT(DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) ,'%Y-%m-01'), INTERVAL -1 DAY))
Begræns derefter resultaterne til restaurant_id'er, der har færre bookinger end dette:
HAVING COUNT(DISTINCT o2.Date) < DAY(DATE_ADD(DATE_FORMAT(DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) ,'%Y-%m-01'), INTERVAL -1 DAY))
Eksempel på begge på SQL Fiddle