plexcell
plexcell

Reputation: 1677

MySql Query Join 3 tables with empty rows

I want to list every product in database with visitor tracking and sales info by user id.

Here is what I got so far:
http://www.sqlfiddle.com/#!2/ec506/19

SELECT products.product_name,
       tracking.unique_hits,
       tracking.total_hits,
       COUNT(sales.product_id) as total_sales,
       SUM(sales.amount) as total_revenue
FROM products
INNER JOIN tracking ON products.id = tracking.product_id
INNER JOIN sales ON products.id = sales.product_id
WHERE products.vendor_id = 0;

It outputs this:

|   PRODUCT_NAME | UNIQUE_HITS | TOTAL_HITS | TOTAL_SALES | TOTAL_REVENUE |
|----------------|-------------|------------|-------------|---------------|
| test product 1 |          42 |         52 |           3 |            30 |

But I want it to output products without sales also, so it should output something like this:

|   PRODUCT_NAME | UNIQUE_HITS | TOTAL_HITS | TOTAL_SALES | TOTAL_REVENUE |
|----------------|-------------|------------|-------------|---------------|
| test product 1 |          42 |         52 |           3 |            30 |
| test product 2 |          10 |         13 |           0 |             0 |

Or

|   PRODUCT_NAME | UNIQUE_HITS | TOTAL_HITS | TOTAL_SALES | TOTAL_REVENUE |
|----------------|-------------|------------|-------------|---------------|
| test product 1 |          42 |         52 |           3 |            30 |
| test product 2 |           0 |          0 |           0 |             0 |

In case there is no even visitor tracking data at table.

I have no idea how to do it. Some help needed! :)

Upvotes: 0

Views: 62

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

Just switch to left outer join:

SELECT products.product_name,
       tracking.unique_hits,
       tracking.total_hits,
       COUNT(sales.product_id) as total_sales,
       coalesce(SUM(sales.amount), 0) as total_revenue
FROM products
LEFT OUTER JOIN tracking ON products.id = tracking.product_id
LEFT OUTER JOIN sales ON products.id = sales.product_id
WHERE products.vendor_id = 0
GROUP BY products.product_name, tracking.unique_hits, tracking.total_hits;

EDIT:

Thanks to M Khalid for the group by. I would write this query with table aliases to make it easier to read:

SELECT p.product_name, t.unique_hits, t.total_hits,
       COUNT(s.product_id) as total_sales,
       coalesce(SUM(s.amount), 0) as total_revenue
FROM products p LEFT OUTER JOIN
     tracking t
     ON p.id = t.product_id LEFT OUTER JOIN
     sales s
     ON p.id = s.product_id
WHERE p.vendor_id = 0
GROUP BY p.product_name, t.unique_hits, t.total_hits;

Upvotes: 3

Related Questions