MySQL选择sum with group by给出整数结果

时间:2009-10-30 09:32:55

标签: mysql group-by

我有两张桌子:

CREATE TABLE `product_det` (
  `id` bigint(12) unsigned NOT NULL AUTO_INCREMENT,
  `prod_name` varchar(64) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `product_det` (`id`,`prod_name`) VALUES 
 (1,'Pepper'),
 (2,'Salt'),
 (3,'Sugar');

CREATE TABLE `product_oper` (
  `id` bigint(12) unsigned NOT NULL AUTO_INCREMENT,
  `prod_id` bigint(12) unsigned NOT NULL,
  `prod_quant` decimal(16,4) NOT NULL DEFAULT '1.0000',
  `prod_value` decimal(18,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `product_oper` (`id`,`prod_id`,`prod_quant`,`prod_value`) VALUES 
 (12,2,'3.0000','26.14'),
 (13,2,'0.0450','26.23'),
 (14,2,'0.0300','26.14'),
 (10,1,'0.0600','13.20'),
 (11,1,'0.0600','13.20');

我想找到每个产品的数量和价值,将第二个表中的值相加。

我的查询是:

SELECT product_det.*, SUM(in_out.p_q) as q, SUM(in_out.p_val) AS val
 FROM
 (SELECT product_oper.prod_id as p_id, SUM(product_oper.prod_quant) as p_q, SUM(product_oper.prod_quant*product_oper.prod_value) as p_val
   FROM product_oper
   GROUP BY product_oper.prod_id
 ) AS in_out
 LEFT JOIN product_det ON in_out.p_id=product_det.id
 GROUP BY in_out.p_id
 HAVING q<>0.00  ORDER BY val;

我得到的结果是:

id,    prod_name,       q,   val
1,     'Pepper',   0.1200,    2
2,     'Salt',     3.0750,   80

哪个错误,列val中的值是整数,它们不应该是整数。

但是,内部选择会给出下一个结果:

p_id,    p_q,     p_val
1,    0.1200,   1.584000
2,    3.0750,  80.384550

问题是:当我从子查询中选择时,为什么我得到val的整数值?为什么q不是整数?

我需要使用子查询,因为我的原始查询是这样的:

SELECT ... FROM (SELECT ... UNION SELECT ...) AS in_out GROUP BY in_out.p_id

我有MySQL版本5.1.39

1 个答案:

答案 0 :(得分:0)

您是否尝试将字段转换为小数?不幸的是,浮点数不可用,但十进制是从版本5.0.8。

SELECT product_det.*, SUM(in_out.p_q) as q, SUM(CAST(in_out.p_val AS DECIMAL)) AS val

并在内部选择;

...CAST(SUM(product_oper.prod_quant*product_oper.prod_value) AS DECIMAL) as p_val...

只是一个想法。