0

我有三个包含这些字段的表:

product_viewsProductMasterID, Date

product_clicksProductMasterID, Date

product_masterProductMasterID, Category

每当有人在我的网站上查看产品时,它都会在product_views. 每当有人点击我网站上的产品时,它都会添加一行product_clicks

我正在尝试编写一个 SQL 查询(在 MySQL/PHP 中),它将向我展示产品的受欢迎程度。受欢迎程度是它被查看和点击的次数加在一起。我还希望能够选择一个日期范围,并在某个类别内。

我可以让它在没有日期/类别限制的情况下工作。我现在正在尝试添加日期范围。这是我到目前为止所拥有的,因为上周很受欢迎:

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"

除了它不起作用,它不会产生任何结果。但是,如果我删除其中任何一个WHERE子句,那么由于某种原因它确实有效,但我需要它们两个。所以我的问题是:

  1. 如何使它与两个WHERE子句一起使用
  2. 如何进行类别部分,例如仅选择具有“食品”类别的产品。我想我必须在product_master桌子的某个地方加入,但看起来很棘手。

任何帮助将不胜感激。

谢谢

4

1 回答 1

0

如果您想使用JOIN,这是一个解决方案:

询问:

SELECT M.PMID, M.CATEGORY, 
(COALESCE(V.VCNT,0) +
COALESCE(C.CCNT,0)) AS TOTAL_COUNT
FROM Master M
LEFT JOIN (SELECT PMID, COUNT(*) AS VCNT
           FROM VIEWS
           WHERE DATE between 
           DATE_ADD(NOW(), INTERVAL - 7 DAY)
           and now()
           GROUP BY PMID) V
ON V.PMID = M.PMID
LEFT JOIN (SELECT PMID, COUNT(*) AS CCNT
           FROM CLICKS
           WHERE DATE between 
           DATE_ADD(NOW(), INTERVAL - 7 DAY)
           and now()
           GROUP BY PMID) C
ON C.PMID = M.PMID
GROUP BY M.PMID
;

结果:

| PMID | CATEGORY | TOTAL_COUNT |
---------------------------------
|    1 |    Shoes |           6 |
|    2 |    Books |           4 |
|    3 |     Food |           3 |

使用 UNION 并仅用于 SQL 部分:

SELECT ID, COUNT(*) AS Popularity FROM 
(
    (SELECT product_views.ProductMasterID AS ID, count(*) 
         FROM product_views 
         WHERE product_views.Date BETWEEN '".date('Y-m-d',strtotime('now'))."' 
            AND '".date('Y-m-d',strtotime('-7days'))."'"."
         GROUP BY product_views.ProductMasterID)

UNION ALL 

    (SELECT product_clicks.ProductMasterID AS ID, COUNT(*)
        FROM product_clicks 
        WHERE product_clicks.Date BETWEEN '".date('Y-m-d',strtotime('now'))."' 
           AND '".date('Y-m-d',strtotime('-7days'))."'".") a
     GROUP BY product_clicks.ProductMasterID)

GROUP BY ProductMasterID 
ORDER BY Popularity DESC LIMIT 100"

这个怎么样?

SELECT M.PMID, M.CATEGORY, COUNT(V.PMID), COUNT(C.PMID)
FROM MASTER M
LEFT JOIN VIEWS V
ON V.PMID = M.PMID
LEFT JOIN CLICKS C
ON C.PMID = M.PMID
WHERE V.DATE BETWEEN NOW() AND NOW() INTERVAL - 7 DAY
AND C.DATE BETWEEN NOW() AND NOW() INTERVAL 7 DAY
GROUP BY M.PMID, V.DATE, C.DATE
;

于 2013-01-17T12:32:06.543 回答