title: SQl query calculations across multiple tables
body: <p>OK, I have 3 database tables at the moment:</p>
  
  <ul>
  <li>users
  <ul>
  <li>id: 1, 2</li>
  <li>name: User1, User2</li>
  </ul></li>
  <li>companies
  <ul>
  <li>id: 1, 2, 3</li>
  <li>share_price: 10.00, 0.45, 5.98</li>
  </ul></li>
  <li>portfolios
  <ul>
  <li>user_id: 1, 1, 2</li>
  <li>company_id: 1, 2, 1</li>
  <li>amount_of_shares: 200, 100, 30</li>
  </ul></li>
  </ul>
  
  <p>Just so you know, this is for a basic stock market simulation. I need to get the top 5 users based on their total portfolio values, which are calculated as such:</p>
  
  <p><code>companies.share_price * portfolios.amount_of_shares</code></p>
  
  <p>Keeping in mind that 1 user can have stock from multiple companies in his portfolio, it seems like a waste to select all the data and then loop through it in PHP, because theoretically I could have about 200 companies... So I was wondering if it's possible to write an SQL query that calculates the value of each companie's stock owned and then sums all of those values up to produce only one variable, so I can do ORDER BY and LIMIT 5 (get the Top5 performers)</p>
  
  <p>EDIT: I'm using CodeIgniter for this project, if that makes a difference.</p>