简体   繁体   English

从两个具有相同列名(总计)的表(销售/费用)中选择

[英]Selecting from two tables (sales/expenses) with the same column name (total)

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. 其他所有东西都设置得很完美,我之前从未不必调用多个表。

Eg of How I am echoing within my HTML: 例如,我如何在HTML中回显:

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

Thanks! 谢谢!

EDIT: attached a picture of my nonsense :) 编辑:附上我胡说八道的图片:) 在此处输入图片说明

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: 由于您要为每个字段指定一个AS子句,因此需要将回显修改为:

<? 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";

Probably you should use two separate queries 可能您应该使用两个单独的查询

otherwise you get Cartesian product. 否则,您将得到笛卡尔积。

More info: http://en.wikipedia.org/wiki/Join_(SQL) 更多信息: http : //en.wikipedia.org/wiki/Join_(SQL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM