I have three tables with these fields:
product_views: ProductMasterID, Date
product_clicks: ProductMasterID, Date
product_master: ProductMasterID, Category
Anytime someone views a product on my site, it adds a row to product_views.
Anytime someone clicks on a product on my site, it adds a row to product_clicks
I am trying to write a SQL query (in MySQL/PHP) that will show me the popularity of products. Popularity is how many times it was viewed and clicked added together. I want to be able to also choose a date range, and within a certain category.
I can make it work without the date/category constrictions. I am now trying to add in the date range. This is what I have so far, for popularity of the last week:
SELECT *, COUNT(*) AS Popularity FROM
(SELECT product_views.ProductMasterID, product_views.Date
FROM product_views
WHERE product_views.Date BETWEEN '".date('Y-m-d',strtotime('now'))."'
AND '".date('Y-m-d',strtotime('-7days'))."'"."
UNION ALL
SELECT product_clicks.ProductMasterID,product_clicks.Date
FROM product_clicks
WHERE product_clicks.Date BETWEEN '".date('Y-m-d',strtotime('now'))."'
AND '".date('Y-m-d',strtotime('-7days'))."'".") a
GROUP BY ProductMasterID ORDER BY Popularity DESC LIMIT 100"
Except that it doesnt work, it produces no results. However, if I delete either one of the WHERE clauses, then it does work for some reason, but I need both of them. So my questions are:
- How to make it work with both
WHEREclauses - How to do the category part e.g. selecting only products which have a category of ‘Food’. I think I would have to do a join somewhere with the
product_mastertable, but looks tricky.
Any help would be greatly appreciated.
Thanks
If you want to use a JOIN, here is a solution:
Query:
Results:
Using the UNION and just for the SQL part:
How about this?