使用UNION,SELECT和JOIN进行SQL查询

时间:2013-01-17 12:23:08

标签: mysql select join union-all

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

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. 一起使用
  3. 如何进行类别部分,例如仅选择具有“食品”类别的产品。我想我必须在product_master表的某个地方进行连接,但看起来很棘手。
  4. 非常感谢任何帮助。

    由于

1 个答案:

答案 0 :(得分: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
;

<击>