mysql选择查询问题
我们有这样一个数据库:mysql选择查询问题,mysql,sql,group-by,sum,Mysql,Sql,Group By,Sum,我们有这样一个数据库: 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 I
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);
我们的任务是:
获得所有付款总额小于1000的工作
因此,我们应该把工作分为“a”、“c”和“d”。但我们的疑问是:
SELECT job
FROM jobs j
JOIN payments p ON j.id=p.job_id
GROUP BY job_id
HAVING sum(amount) < 1000;
不包括没有任何报酬的工作。所以我们得到的结果只有“a”
我们应该如何构造查询以获取付款总额小于1000的所有作业?我认为您可能需要左联接
您需要将作业关联到总和查询的结果:
SELECT *
from job j
join (SELECT job_id, sum(amount)
FROM jobs j
JOIN payments p ON j.id=p.job_id
GROUP BY job_id
HAVING sum(amount) < 1000) x on x.job_id = j.job_id
union
SELECT * from job where job_id not in (select job_id from payments);
工会也会找到没有报酬的工作,只要你使用案例陈述来确保 对于没有付款的工作,金额计算为零。否则,amount将为null,因此不能与HAVING子句中的1000进行比较
SELECT j.id job_id ,sum(case when amount is null then 0 else amount end)
FROM jobs j LEFT JOIN payments p ON j.id=p.job_id
GROUP BY j.id
HAVING sum(case when amount is null then 0 else amount end) < 1000;
注意:这在oracle上有效,但不确定mysql上的确切语法。Left join在这种情况下没有帮助。
SELECT j.id job_id ,sum(case when amount is null then 0 else amount end)
FROM jobs j LEFT JOIN payments p ON j.id=p.job_id
GROUP BY j.id
HAVING sum(case when amount is null then 0 else amount end) < 1000;