Mysql multiply count
I have a query, which will lo开发者_开发问答op through an orders table, and as a sub query, will also count the number of rows in another table using a foreign key.
SELECT eo.*, (
SELECT COUNT(*)
FROM ecom_order_items eoi
WHERE eo.eo_id = eoi.eoi_parentid
AND eoi.site_id = '1'
) AS num_prods
FROM ecom_orders eo
WHERE eo.site_id = '1' AND eo_username = 'testuser'
Now, on the ecom_order_items table, it has a eoi_quantity field. I want the query to display the number of products for each order, taking into account the quantity field.
SELECT eo.*, (
SELECT COUNT(*) * eoi.eoi_quantity
FROM ecom_order_items eoi
WHERE eo.eo_id = eoi.eoi_parentid
AND eoi.site_id = '1'
) AS num_prods
FROM ecom_orders eo
WHERE eo.site_id = '1' AND eo_username = 'testuser'
However when I try this, it just gives me the same number as before. For the order I am testing on, it has 2 items, one with quantity 1, the other with quantity as 10, and num_prod is returning as 2 on both queries.
Any ideas? :)
If the value of eoi.eoi_quantity consists of multiple values, 1 and 10, only one of them will be selected and multiplied by COUNT(*). So you are getting the result 1 * 2.
As COUNT(*) = 2 for two items, do you want the result 2 * 1 + 2 * 10? It doesn't seem right to me. I'm thinking you want to count the total quantity over all the relevant orders, so why not use SUM(eoi.eoi_quantity) to get 1 + 10 instead? Thus you would have:
SELECT eo.*, (
SELECT SUM(eoi.eoi_quantity)
FROM ecom_order_items eoi
WHERE eo.eo_id = eoi.eoi_parentid AND eoi.site_id = '1'
) AS num_prods
FROM ecom_orders eo
WHERE eo.site_id = '1' AND eo_username = 'testuser';
But this is still going to get you the same value for each column. In fact, a subquery like (SELECT eo.*,...) will result in an error if it returns more than one row.
That's why Johan suggested that you would want to join the tables. You need to join the tables to be sure that the rows are properly linked and then group them by the id's you want for each row. How about:
SELECT eo.*, SUM(eoi.eoi_quantity)
FROM ecom_orders eo JOIN ecom_order_items eoi ON eo.eo_id = eoi.eoi_parentid
WHERE eo.site_id = '1'
AND eo_username = 'testuser'
GROUP BY eo.eo_id;
Rewrite the query into:
SELECT eo.*, sum(eoi.eoi_quantity) as sales
FROM ecom_orders eo
INNER JOIN ecom_order_items eoi ON (eo.eo_id = eoi.eoi_parentid)
WHERE eo.site_id = '1' AND eoi.site_id = '1' AND eo_username = 'testuser'
GROUP BY eo.eo_id;
Because the count(*) for each individual item is 1, count(*) * quantity
is the same as sum(quantity)
.
精彩评论