2014-04-24 33 views
0

我想列出數據庫中的每個產品,其中包含訪問者跟蹤和銷售信息(按用戶標識)。MySql查詢連接3個空行行表

這是我走到這一步:
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 | 

如果在表格中沒有訪客跟蹤數據。

我不知道該怎麼做。需要一些幫助! :)

+2

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/ – Barmar

+0

[**見演示* *](http://www.sqlfiddle.com/#!2/ec506/28) –

回答

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哈立德爲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; 
+2

@MKhalidJunaid。 。 。這是一個敏銳的觀察。我甚至沒有意識到它錯過了。 –