We have a DB like this:
CREATE TABLE `jobs` (
`id` int NOT NULL AUTO_INCREMENT,
`job` varchar(255),
PRIMARY KEY (`id`)
);
INSERT INTO `jobs` VALUES
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d');
CREATE TABLE `payments` (
`job_id` int,
`amount` int
);
INSERT INTO `payments` VALUES
(1,100),
(1,100),
(2,600),
(2,600);
Our task is:
Get all jobs, where sum of payments is smaller than 1000.
As a result we should jobs 'a','c' and 'd'. But our query:
SELECT job
FROM jobs j
JOIN payments p ON j.id=p.job_id
GROUP BY job_id
HAVING sum(amount) < 1000;
excludes jobs without any payments. So a result we get only 'a'.
How should we construct the query to get all jobs where sum of payments is smaller than 1000?