Mysql DISTINCT和COUNT查询

时间:2016-02-12 15:10:59

标签: mysql count distinct

我在查询输出我想要的方式时遇到问题,

SELECT 
    `orders`.`item_id`, 
    `products`.`item_code`, 
    `products`.`item_name`, 
    `orders`.`quantity` 
FROM 
    `orders` 
    JOIN `products` ON `orders`.`item_id` = `products`.`id` 
    JOIN `suppliers` ON `products`.`supplier_ref` = `suppliers`.`supplier_ref` 
WHERE 
    `suppliers`.`id` = 159 
    AND `orders`.`order_status` = 'NOTED'

返回结果:

item_id item_code item_name            quantity
1271    RA001G    Green Mop Bucket 12L 2
1270    RA001     Blue Mop Bucket 12L  1
1270    RA001     Blue Mop Bucket 12L  1

但我希望它能带回不同的item_id,并将数量加在一起,当我尝试添加不同的数据时,我最终只返回一行。

2 个答案:

答案 0 :(得分:2)

如果您想总结相同商品的数量,请尝试分组而不是item_id。像这样:

SELECT 
    `orders`.`item_id`, 
    `products`.`item_code`, 
    `products`.`item_name`, 
    sum(`orders`.`quantity`) as quantity, 
FROM 
    `orders` 
    JOIN `products` ON `orders`.`item_id` = `products`.`id` 
    JOIN `suppliers` ON `products`.`supplier_ref` = `suppliers`.`supplier_ref` 
WHERE 
    `suppliers`.`id` = 159 
     AND `orders`.`order_status` = 'NOTED'
  GROUP BY `orders`.`item_id`, 
      `products`.`item_code`, 
      `products`.`item_name`

答案 1 :(得分:0)

请使用分组

 SELECT 
`orders`.`item_id`, 
`products`.`item_code`, 
`products`.`item_name`, 
 sum(`orders`.`quantity`) as quantity
 FROM 
  `orders` 
   JOIN `products` ON `orders`.`item_id` = `products`.`id` 
   JOIN `suppliers` ON `products`.`supplier_ref` =   `suppliers`.`supplier_ref` 
WHERE 
 `suppliers`.`id` = 159 AND `orders`.`order_status` = 'NOTED'
group by 
 `orders`.`item_id`;