简体   繁体   English

使用PHP从MySQL中的多个表中添加总值

[英]Adding total values from multiple table in MySQL with php

I have 2 tables, I need to sum up the total value from each tables price column. 我有2张桌子,我需要总结每个桌子价格列的总价值。 I did some research on Stack but the solutions I saw were too long and did not seems efficient enough code. 我对Stack进行了一些研究,但是看到的解决方案太长,而且似乎效率不够。 With MySQL I am trying to get the total value from StoreCoins plus the total value from StoreMemorabilia and the total value from supplies then I want the sum of the total of both table's column. 使用MySQL,我试图从StoreCoins中获取总价值,再从StoreMemorabilia中获取总价值,并从供应中获取总价值,然后我想要两个表的列的总和。 This first code is currently not working... 目前第一个代码不起作用...

if($results = $this->dbConn->query("SELECT SUM(column) AS InventoryValue FROM (
                                        SELECT SUM(column) AS value FROM StoreCoins
                                        UNION ALL
                                        SELECT SUM(column) AS value FROM StoreMemorabilia
                                        ) allposts")){
while($data = $results->fetch_assoc()){
    $totalVal = $data['InventoryValue'];
    $totalVal .= ".00";

I need to know what I am doing wrong in the code above. 我需要知道我在上面的代码中做错了什么。

On another note (this is php related): I have the following script that once the correct value is returned it decides where to put the commas for dollar values. 另一方面(这是与php相关的):我有以下脚本,一旦返回正确的值,它就会决定将美元值的逗号放在何处。 I would like a recommendation to a much more efficient way to create this function and its results. 我想推荐一种更有效的方法来创建此功能及其结果。 The switch statement works just fine and does what I need it to do, I just want a more eloquent way of writing this. switch语句工作得很好,可以执行我需要做的事情,我只是想以一种更加雄辩的方式编写此语句。

switch(strlen($Val)){
    case 7:
        $rem = substr($Val, 1, 6);
        $Val = substr_replace($Val, ",", 1);
        $Val = $Val.$rem;
        break;
    case 8:
        $rem = substr($Val, 2, 6);
        $Val = substr_replace($Val, ",", 2);
        $Val = $Val.$rem;
        break;
    case 9:
        $rem = substr($Val, 3, 6);
        $Val = substr_replace($Val, ",", 3);
        $Val = $totalVal.$rem;
        break;
    case 10:
        $rem = substr($Val, 1, 10);
        $Val = substr_replace($Val, ",", 1);
        $Val = $Val.$rem;
        $rema = substr($Val, 5, 6);
        $Val = substr_replace($Val, ",", 5);
        $Val = $Val.$rema;
}

I hope the following is what you are after: 我希望以下是您所追求的:

select (
    ( select sum(`price`) from `StoreCoins` ) 
        + 
    ( select sum(`price`) from `StoreMemorabilia` )
) as 'total';

Change the query like this 像这样更改查询

SELECT SUM(column) FROM ( 
SELECT SUM(column) AS value FROM StoreCoins

UNION 

SELECT SUM(column) AS value FROM StoreMemorabilia
) InventoryValue

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

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