我有2个表,我需要总结每个表价格列的总价值。我对Stack进行了一些研究,但我看到的解决方案太长了,而且代码看起来效率不高。 使用MySQL我试图从StoreCoins获得总价值加上StoreMemorabilia的总价值和供应品的总价值然后我想要两个表格列总和的总和。第一个代码目前无效...
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";
我需要知道上面的代码中我做错了什么。
另一个注意事项(这与php有关): 我有以下脚本,一旦返回正确的值,它决定将逗号放在美元值的位置。我想建议一个更有效的方法来创建这个功能及其结果。 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;
}
答案 0 :(得分:2)
我希望以下是您的目标:
select (
( select sum(`price`) from `StoreCoins` )
+
( select sum(`price`) from `StoreMemorabilia` )
) as 'total';
答案 1 :(得分:0)
像这样更改查询
SELECT SUM(column) FROM (
SELECT SUM(column) AS value FROM StoreCoins
UNION
SELECT SUM(column) AS value FROM StoreMemorabilia
) InventoryValue