假设我有一张桌子
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:
我尝试了这个查询:
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 |
+---------+---------------+----------║---------+---------------+----------+
║
如何获得必要的信息?
答案 0 :(得分:2)
SELECT site_id, MAX(download_date) AS download_date, count(*)
FROM pages_urls
GROUP BY site_id;