简体   繁体   中英

mysql INNER/LEFT JOIN with UNION ALL

I have a question regarding the use of UNION ALL and INNER JOIN. I found some posts regarding this issue, for example here or there but I did not manage to apply it to my issue. What I am trying to do is to list 1) the products and 2) the difference between orders and deliveries. I have 3 table:

  • product (id, name)
  • orders (id, product, value)
  • deliveries (id, product, value)

I managed to get (almost) what I want using the following:

    SELECT product
,      sum(total)
FROM (
SELECT product
,      SUM(value) as total
FROM orders
GROUP BY product
union all
SELECT product
,      -1 * SUM(value) as total
FROM deliveries
GROUP BY product)
as alias
GROUP BY product
ORDER BY sum(total) DESC

I obtain the following:

  • 1 23
  • 2 33

When I would like to get:

  • computer 23
  • car 33

Meaning the product name instead of the product id. Anyone would have a solution for that? (my INNER JOIN OR LEFT JOIN attempts failed so far) Thanks and regards

Join in the product table:

SELECT p.name, sum(total)
FROM (SELECT o.product, SUM(o.value) as total 
      FROM orders o
      GROUP BY o.product
      union all 
      SELECT d.product, -1 * SUM(d.value) as total 
      FROM deliveries  d GROUP BY d.product
     ) od JOIN
     product p
     on od.product = p.id
GROUP BY p.name
ORDER BY sum(total)  DESC    

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