0

I have a table containing customers and another containing all orders.

I want to display a list of customers and along side show the total value of their orders.

Obviously I could loop through the customers and then using PHP run another query to get each customer's revenue. I don't think this is efficient.

I am looking to achieve something like this:

SELECT username, [SELCT sum(revenue) from orders where userID=userID] from customers

And for this to show output:

bob      10000
jeff     25000
alan     500
2
  • 1
    you can always compare the performance between join and correlated subqueries. Commented Jan 25, 2013 at 16:06
  • The subselect used there is likely to perform slowly Commented Jan 25, 2013 at 16:21

4 Answers 4

1
SELECT  a.username, SUM(b.revenue) totalRevenue
FROM    customers a
        LEFT JOIN Orders b
            ON a.userID = b.UserID
GROUP   BY a.username

This will list all customers with or without Orders.

To further learn more about join, please visit the article below,

Sign up to request clarification or add additional context in comments.

Comments

0

you're close...

 SELECT username, (SELECT sum(revenue) from orders where userID=c.userID) rev 
 from customers c

Comments

0

You can join the tables and the group them by the order name

SELECT o.username, 
       sum(revenue) as sum_revenue
from orders  o
left outer join customers c on c.userid = o.userid
group by o.username

Comments

0

No need for a subselect with that. Try something like this:-

SELECT customers.userID, customers.username, SUM(revenue)
FROM customers INNER JOIN orders ON customers.userID = orders.userID
GROUP BY customers.userID, customers.username

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.