1

这是我在product表格LEFT JOIN上使用的查询,page表格中ONproductidpageidin product.. 非常简单。

SELECT 
COUNT(DISTINCT `p`.`id`) as `quantity`,
DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
FROM
`product` AS `p` 
LEFT JOIN
`page` AS `pg` ON `p`.`id` = `pg`.`productid` 
WHERE
`p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59'
AND
`p`.`group` = '101' 
GROUP BY `day`, `p`.`id` HAVING COUNT(`pg`.`productid`)>=10 
ORDER BY `p`.`created_time`

涉及的两个示例表:

**product**
id  created_time
32  2013-07-09
33  2013-07-09

**page**
id  productid
1   33
2   33
..  ..
20  33
21  32
22  32
..  ..
54  32

现在我的结果集如下所示:

quantity    day
1           2013-07-09
1           2013-07-09
1           2013-07-10

但我希望在UNION不使用和不使用temp表格的情况下获得以下输出:

quantity    day
2           2013-07-09
1           2013-07-10

我的代码示例现在添加了两个表。我需要product十个或更多page分组的数量day

4

3 回答 3

1

我认为那是因为您要p.idgroup by条款中离开。尝试这个:

SELECT COUNT(DISTINCT `p`.`id`) as `quantity`,
       DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
FROM `product` AS `p` LEFT JOIN
     `page` AS `pg`
      ON `p`.`id` = `pg`.`productid` 
WHERE `p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59'
      AND `p`.`group` = '101' 
GROUP BY `day`
HAVING COUNT(`pg`.`productid`)>=10 
ORDER BY `p`.`created_time`
于 2013-07-10T14:11:18.073 回答
1

不要值,GROUP BY也可以上idORDER BYday

请注意,在标准 SQL 中或 when is usingday中不可用。MySQL 允许它作为扩展,但它具有误导性GROUP BYsql_mode"only_full_group_by"

SELECT 
    COUNT(*) as `quantity`,
    DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
FROM
   `product` AS `p` 
   JOIN
   `page` AS `pg` ON `p`.`id` = `pg`.`productid` 
WHERE
   `p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59'
   AND
   `p`.`group` = '101' 
GROUP BY
   `pg`.`productid`, DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
HAVING
   COUNT(*) >= 10 
ORDER BY
   `day`;
于 2013-07-10T14:11:57.290 回答
1

我找到了我的查询的解决方案:

SELECT
COUNT(`p`.`id`) as `quantity`,
DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day`
FROM
`product` AS `p`
INNER JOIN 
(
SELECT 
    `productid` AS `id`,
    count(id) AS pagesNR 
FROM 
    `page`
GROUP BY 
    `productid` HAVING COUNT(`id`) >= 10
)
AS 
`pg` USING (`id`)
WHERE
    `p`.`created_time` BETWEEN '2013-07-03 00:00:00' AND '2013-07-10 23:59:59'
AND
    `p`.`group` = '101'
GROUP BY 
    `day`
ORDER BY 
    `created_time`

感谢我同事 Daniël Versteeg 的朋友

于 2013-07-11T13:17:15.237 回答