I have two tables that have this design
Invoices
-------
invoice_id
is_delivered
Data => (1, 'yes')
Invoice_products
----------------
ip_id
invoice_id
product_id
price
Data=> (1,1,1,5000), (2,1,2,7000)
Now what I want is all the columns of Invoices table and sum of prices in the other table. Something like this
invoice_id = 1
is_delivered = 'yes'
total = 12000
I tried this but the result wasn't correct.
SELECT * FROM invoices i INNER JOIN (SELECT invoice_id, SUM(price) AS total FROM invoice_products p ) AS t ON t.invoice_id = i.invoice_id;
I am not very good in mysql but I tried. Can someone care to answer with explanation?
You have some syntax errors, and you don't need sub-query.
You can just select all from invoice_products
and calculate SUM
- it is easy to do. You have already done it, but don't miss GROUP
clause, it will calculate sums accordingly to distinct invoice_id
. If you don't need it - just omit groub clause.
After that you just need join invoices
table to get some additional information from this table.
The final result will look like this:
SELECT i.invoice_id, i.is_delivered, p.invoice_id, SUM(p.price) AS total
FROM invoice_products AS p
INNER JOIN invoices AS i ON p.invoice_id = i.invoice_id
GROUP BY p.invoice_id;
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.