对于GROUP BY中的每一行,MySQL使用COUNT获取MAX值

时间:2013-06-01 23:44:26

标签: mysql sql group-by

假设我有一张桌子

           pages_urls
+----+---------+---------------+
| id | site_id | download_date |
+----+---------+---------------+
|  1 |       1 | 2012-01-01    |
|  2 |       1 | 2012-12-31    |
|  3 |       2 | 2012-01-01    |
|  4 |       2 | 2012-12-31    |
+----+---------+---------------+

对于我想要选择的每个site_id:

  1. 上次下载日期
  2. 此网站表格中的记录数
  3. 我尝试了这个查询:

    SELECT
        pages_urls.site_id,
        max_table.download_date,
        COUNT(*)
    FROM
        pages_urls
    LEFT JOIN
    (
    SELECT
        site_id,
        MAX(download_date) AS download_date
    FROM
        pages_urls AS max_pages_urls
    WHERE
        max_pages_urls.site_id=site_id
    ) AS max_table
    ON
        pages_urls.site_id=max_table.site_id
    GROUP BY
        site_id;
    

    但是我得到了这个而不是期望的结果:

                desired result           ║            my query result         
    +---------+---------------+----------║---------+---------------+----------+
    | site_id | download_date | COUNT(*) ║ site_id | download_date | COUNT(*) |
    +---------+---------------+----------║---------+---------------+----------+
    |       1 | 2012-12-31    |        2 ║       1 | 2012-12-31    |        2 |
    |       2 | 2012-12-31    |        2 ║       2 | NULL          |        2 |
    +---------+---------------+----------║---------+---------------+----------+
                                         ║
    

    fiddle with table and query

    如何获得必要的信息?

1 个答案:

答案 0 :(得分:2)

SELECT site_id, MAX(download_date) AS download_date, count(*)
FROM pages_urls
GROUP BY site_id;

SQLFiddle demo