需要有关mysql查询的帮助

时间:2011-04-15 19:52:58

标签: mysql

我开发了一个mysql查询,告诉我在指定的时间范围内购买了每个产品的次数。我正在尝试弄清楚如何将其与我的综合浏览量跟踪表相结合,以便我可以计算每种产品的转换率。这是原始查询:

SELECT SUM( op.products_quantity ) AS num_sold, SUM( op.final_price * op.products_quantity ) AS total_sales, p.products_model, pd.products_name, p.products_id
    FROM orders_products AS op
    JOIN products AS p
    JOIN products_description AS pd
    JOIN orders as o
    WHERE p.products_id = op.products_id
    AND p.products_id = pd.products_id
    AND op.orders_id = o.orders_id
    AND o.date_purchased BETWEEN '2011-01-15' AND '2011-04-15"'
    GROUP BY p.products_id
    ORDER BY total_sales DESC

我有另一个查询,它为我提供了每个产品的网页浏览量:

SELECT pv.products_id, count( pv.timestamp )
FROM products_visits AS pv
WHERE pv.timestamp
BETWEEN '2011-01-15'
AND '2011-04-17'
GROUP BY products_id

需要注意的是,视图数据刚刚开始被收集,因此我们希望返回结果,即使给定的product_id不在视图表中,但是在购买表中。

如何将这些查询合并到一个查询中?

2 个答案:

答案 0 :(得分:0)

您需要使用LEFT JOIN:“首先”获取所有产品及其销售数据,然后加入视图数据(如果存在)。

试试这个:

SELECT p.products_id, 
count( pv.timestamp ) AS views,
p.products_model AS model,
SUM( op.products_quantity ) AS num_sold,
SUM( op.final_price * op.products_quantity ) AS total_sales,
pd.products_name
FROM products AS p
LEFT JOIN products_visits AS pv 
     ON pv.products_id = p.products_id
     AND pv.timestamp BETWEEN '2011-01-15' AND '2011-04-17'
JOIN orders_products AS op
     ON p.products_id = op.products_id
JOIN products_description AS pd
     ON p.products_id = pd.products_id
JOIN orders as o
     ON op.orders_id = o.orders_id
     AND o.date_purchased BETWEEN '2011-01-15' AND '2011-04-17'
GROUP BY p.products_id
ORDER BY total_sales DESC

答案 1 :(得分:0)

您需要针对子查询LEFT OUTER JOIN。我认为这将完成这项工作:

SELECT 
  SUM( op.products_quantity ) AS num_sold, 
  SUM( op.final_price * op.products_quantity ) AS total_sales, 
  p.products_model, pd.products_name, 
  p.products_id,
  visits.visits
FROM orders_products AS op
  JOIN products AS p
  JOIN products_description AS pd
  JOIN orders as o
  LEFT OUTER JOIN (
     SELECT pv.products_id, count( pv.timestamp ) AS visits
     FROM products_visits AS pv
     WHERE pv.timestamp BETWEEN '2011-01-15' AND '2011-04-17'
     GROUP BY products_id
  ) visits ON p.products_id = visits.products_id
WHERE p.products_id = op.products_id
  AND p.products_id = pd.products_id
  AND op.orders_id = o.orders_id
  AND o.date_purchased BETWEEN '2011-01-15' AND '2011-04-15"'
GROUP BY p.products_id
ORDER BY total_sales DESC