mysql查询从另一个表中取总和并选择

时间:2016-08-21 02:08:54

标签: mysql

我有两个表,我想构建一个查询,只选择表交付不满足数量的订单的结果:

orders

id item quantity
1  a    15
2  b    5
3  c    6

deliveries

id order_id quantity
1  2        3
2  2        1
3  2        1
4  3        3

我想要这样的事情:

SELECT * FROM `orders` 
WHERE `quantity`>(SELECT SUM(`quantity`) 
FROM `deliveries` 
WHERE `order_id`=orders.id);

结果应该是这样的:

id item quantity
1  a    15
3  c    6

4 个答案:

答案 0 :(得分:1)

如果订单表每个订单只有一行,请尝试以下查询。我认为您还需要订购没有交货的订单。

SELECT 
    ord.*
FROM orders ord LEFT JOIN
  (SELECT 
    order_id, sum(quantity) AS 'totalDelivered'
   FROM 
    deliveries 
   GROUP BY order_id) 
    AS delv 
   ON ord.id = delv.order_id
WHERE (delv.totalDelivered < ord.quantity OR delv.order_id IS NULL)

答案 1 :(得分:1)

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子句允许用户使用别名&#39; d列名。

答案 2 :(得分:1)

您也可以尝试这种方式:

SELECT o.id, o.item, o.quantity
FROM orders o
INNER JOIN (SELECT 
    o1.id, 
    IFNULL(SUM(d.quantity), 0) quantity 
FROM orders o1
LEFT JOIN deliveries d ON d.order_id = o1.id
GROUP BY d.order_id) p ON p.id = o.id
AND o.quantity > p.quantity

答案 3 :(得分:1)

使用&#34; WHERE&#39;数量&#39;&gt;(SELECT SUM(&#39;数量&#39;)&#34;?您获得所有数量的总和表,因此无法获得一个结果。您的查询应该是这样的:

这将完成或完成所有交付:

SELECT orders.* FROM orders INNER JOIN deliveries ON orders.id=deliveries.order_id WHERE orders.quantity=deliveries.quantity

这将获得尚未完成或完成的所有交付:

    SELECT orders.* FROM orders INNER JOIN deliveries ON orders.id=deliveries.order_id WHERE orders.quantity>deliveries.quantity