简体   繁体   中英

subtract from two different table

i have 3 tables tables "productlist, sales, return" so let say for example i have 3 sales and 2 return as given below.

this is the ff data from productlist

id | pcode | pname | pdesc | 
 1 |  222  | 33uf  | 10v   | 

this is the ff data from sales

id | pcode | total | profit
 1 |  222  |  200  |  10
 2 |  222  |  100  |  10
 3 |  222  |  200  |  10

this is the ff data from return

id | pcode | total | lose
 3 |  222  |  200  |  10
 4 |  222  |  100  |  10

My problem is this . I want to select data from productlist and sum the "total" and "profit" Value from sales and sum the "total" and "lose" value from return. And then subtracting my two table to get the result. The expected result must be something like this.

id | pcode | pname | pdesc | total | profit |
 1 |  222  | 33uf  | 10v   | 200   |  10    |

I have this ff code but I can't subtract "total" from sales to "total" from return and "profit" from sales and "lose" from return.

$result = mysql_query("SELECT 
    productlist.*, 
    SUM(sales.total)-SUM(return.total) as total, 
    SUM(sales.profit)-SUM(return.lose) as profit

FROM productlist
LEFT JOIN sales ON sales.pcode = productlist.pcode AND return ON return.pcode = productlist.pcode
GROUP BY pcode
    ORDER BY total ASC");

You seem to be trying to join two tables with AND , that's not quite right ;)

Try this:

...
LEFT JOIN `sales` USING (`pcode`)
LEFT JOIN `return` USING (`pcode`)
...

I'm not completely certain this'll work, it may complain of column `pcode` is ambiguous . If this happens, try this instead:

...
LEFT JOIN `sales` ON `sales`.`pcode` = `productlist`.`pcode`
LEFT JOIN `return` ON `return`.`pcode` = `productlist`.`pcode`
...

The structure of your query is not going to return the right results. Not matter how you fix the syntax, you will still be getting a cartesian product between the sales and returns for a given product.

One fix is to do aggregations before the joins:

SELECT pl.*,
       (coalesce(s.total, 0) - coalesce(r.total, 0)) as total,
       (coalesce(s.profit, 0) - coalesce(r.lose, 0)) as profit
FROM productlist pl left join
     (select pcode, sum(total) as total, sum(profit) as profit
      from sales
      group by pcode
     )
     on s.pcode = pl.pcode left join
     (select pcode, sum(total) as total
      from return
      group by pcode
     ) r
     on r.pcode = pl.pcode
ORDER BY total ASC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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