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 |
如果在表格中沒有訪客跟蹤數據。
我不知道該怎麼做。需要一些幫助! :)
http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/ – Barmar
[**見演示* *](http://www.sqlfiddle.com/#!2/ec506/28) –