create table orders
( id int not null,
item varchar(100) not null,
quantity int not null
);
insert orders values
(1,'a',15),
(2,'b',5),
(3,'c',6);
create table deliveries
( id int not null,
order_id int not null,
quantity int not null
);
insert deliveries values
(1,2,3),
(2,2,1),
(3,2,1),
(4,3,3);
查詢:
select o.id,o.item,o.quantity as quant_ordered,ifnull(sum(d.quantity),0) as delivered
from orders o
left join deliveries d
on d.order_id=o.id
group by o.id,o.item,o.quantity
having delivered<quant_ordered;
+----+------+---------------+-----------+
| id | item | quant_ordered | delivered |
+----+------+---------------+-----------+
| 1 | a | 15 | 0 |
| 3 | c | 6 | 3 |
+----+------+---------------+-----------+
的having
子句允許使用的alias'd列名。
你想做什麼?我無法理解桌子。你想獲得已經完成的訂單?這意味着所有的訂單是否已經交付?或尚未完成的訂單? –