0

I currently have an Array in PHP with product numbers. Lets call that products. In my database I have a table containing combinations of product numbers and the price that belongs to that product.

Problem: My Array can hold duplicate entries if for instance article #1 is ordered twice.

If I use a query like

SELECT SUM(price) FROM articles WHERE article_number IN (products)

the duplicate entry of 1 get discarded. The query I am looking for gives the sum of 10 + 10 + 12.5 + 9.95.

Is there a way to do this within MySQL?

As a clarification to my data:

products = [1, 1, 2, 3];

articles|  article_number | price
__________________________________
        |  1              |  10.0
        |  2              |  12.5
        |  3              |  9.95

Thank you :)

1
  • You can use array unique function if you have issue with duplications Commented Jun 16, 2015 at 17:59

3 Answers 3

2

winmutt has a solid answer. However, if you don't have such a table to to join with then you could build your query like so:

select sum (p) from (
  (select price as p from articles where article_number = 1)
  union all
  (select price as p from articles where article_number = 1)
  union all
  (select price as p from articles where article_number = 2)
  union all
  (select price as p from articles where article_number = 3)
) s
Sign up to request clarification or add additional context in comments.

Comments

1

If your products were in a table you could do a simple JOIN:

SELECT SUM(price) FROM articles JOIN products on article_number=product_number

Comments

0

I thought there might be an easier way of doing this in SQL. I solved it in PHP by querying all the prices of the array's products and then in iterating over my Array in PHP to sum up the price there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.