tags:

views:

284

answers:

1

I have 2 tables:

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');

I want to find the quantity and value of each product summing the values in the second table.

My query is:

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;

The result I get is:

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

Which is wrong, the values from column val are integers, and they shouldn't be.

However, the inner select gives the next result:

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

The problem is: why I get integer values for val when I select from the subquery? And why q is not integer?

I need to use subqueries, because my original query was like this:

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

I have MySQL version 5.1.39

A: 

Have you tried casting your field to a decimal? Unfortunately float is not available, but decimal is from version 5.0.8.

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

And in the inner select;

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

Just a thought.

Björn
Thanks a lot! It works if I write DECIMAL(18, 2).
True Soft