Question

I tried a few things, and so far this is the only thing not throwing an error, but the results wont echo on my page so I'm not quite sure what's going on.

$query = "SELECT SUM(sales.total) AS sales_total, SUM(expenses.total) AS expenses_total FROM sales,expenses";

Everything else is set up perfectly, I've just never had to call multiple tables before.

E.g. of How I am echoing within my HTML:

<? echo $row['SUM(sales_total)']; ?>
<? echo $row['SUM(expenses_total)']; ?>

Thanks!

EDIT: attached a picture of my nonsense :)enter image description here

Was it helpful?

Solution

Probably you should use two separate queries

otherwise you get Cartesian product.

More info: http://en.wikipedia.org/wiki/Join_(SQL)

OTHER TIPS

This is a cartesian join and won't give you the results that you want.

$query = "SELECT SUM(sales.total) AS sales_total, SUM(expenses.total) AS expenses_total FROM sales,expenses";

You'll need to read up on inner joins to do this properly. Without more details, I can't advise you how to fix that query, other than doing two queries, one for each table. Since you are specifying an AS clause for each field, you'll need to modify your echoes to:

<? echo $row['sales_total']; ?>
<? echo $row['expenses_total']; ?>

Hope that helps!

UPDATE: revising the query to produce the desired results:

$query = "SELECT sales_summary.sales_total,
                 expenses_summary.expenses_total 
          FROM (SELECT SUM(sales.total) AS sales_total 
                  FROM sales) sales_summary, 
               (SELECT SUM(expenses.total) AS expenses_total 
                  FROM expenses) expenses_summary";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top