MySql Query使用空行连接3个表

时间:2014-04-24 19:56:42

标签: mysql sql

我想按用户ID列出数据库中的每个产品,包括访客跟踪和销售信息。

这是我到目前为止所得到的:
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;

输出:

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

但我希望它也可以输出没有销售的产品,所以它应该输出这样的东西:

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

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

如果桌面上没有访客跟踪数据。

我不知道该怎么做。需要一些帮助! :)

1 个答案:

答案 0 :(得分:3)

只需切换到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;

编辑:

感谢M Khalid为group by。我会用表别名编写这个查询,以便于阅读:

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;