mysqljoinmultiplication

How to Display total cost of boxes i.e (no_of_boxes*cost_per_box) against common PID i.e. Product-ID column contained in two different tables?


Cost per box is in the table named products whereas no of boxes is in sales table. PID is common in both tables both are in same schema and database. I want total cost of boxes per PID shown against PID(product id). PID is the primary key.

I was trying this but it didn't work as a syntax

SELECT s.PID, pr.Boxes, (s.Boxes*pr.Cost_per_box) AS Total_Cost_of_Boxes
join products pr 
on pr.PID = s.PID;

I am a beginner so pardon anything silly in the syntax and please provide me the right syntax. One more thing pr.cost_per_box is FLOAT and s.Boxes is NUMERIC. pr. represents products table and s. represents sales table. And I have passed syntaxes before hand SELECT * from sales; and SELECT * from products; .

SELECT s.PID, pr.Boxes, (s.Boxes*pr.Cost_per_box) as Total_Cost_of_Boxes
join products pr 
on pr.PID = s.PID;

was expecting what I mentioned in details. PID | BOXES | TOTAL COST OF BOXES


Solution

  • You have a sales and a product table and you need to join the two. Yet, in your query, you forgot to specify that you want to select from sales s join products p ..., you only added the join part, but not the from and you had the syntax error problem you reported, but it is expected if you have a join without a from in your select.

    So here's a better query:

    SELECT pr.PID, coalesce(sum(s.Boxes), 0) as boxes, coalesce(sum(s.Boxes*pr.Cost_per_box), 0) AS Total_Cost_of_Boxes
    from products pr
    left join sales s
    on pr.PID = s.PID
    group by pr.PID
    

    Explanation: